/**
 * EditorSidebar
 * Renders the editor-side workflow around atlas selection, current annotation
 * metadata, the dynamic trait form, and save or check controls.
 */
import React, { useState, useEffect } from 'react';
import { ScrollArea } from "@/components/ui/scroll-area";
import { useAnnotations } from '../../hooks/useAnnotations';
import AppHeader from './AppHeader';
import AppFooter from './AppFooter';
import Form from '../form/Form';
import { CheckCircle2, AlertCircle, UserX, BookOpen, ChevronDown } from "lucide-react";
import { useLanguage } from '../../context/LanguageContext';
import { getAtlases } from '../../api/generated/index';
import { useQueryClient } from '@tanstack/react-query';
import { useMessageDialog } from '../../hooks/useMessageDialog';
import { buildApiUrl } from '../../utils/api';

export default function EditorSidebar({ state, actions, width, onResizeStart }) {
  const { t, lang } = useLanguage();
  const { confirm } = useMessageDialog();
  const { data: history } = useAnnotations();
  const queryClient = useQueryClient();
  const [availableAtlases, setAvailableAtlases] = useState([]);
  const [showPicker, setShowPicker] = useState(false);

  useEffect(() => {
    const fetchAtlases = async () => {
      try {
        const { data } = await getAtlases();
        setAvailableAtlases(data || []);
      } catch (e) {
        console.error('Failed to load atlas list:', e);
      }
    };
    fetchAtlases();
  }, []);

  const annotations = history?.data?.annotations || history?.annotations || [];
  const isExistingAnnotation = annotations.some(entry => entry.annotationId === state.annotationId);

  const currentAnnotation = annotations.find(entry => entry.annotationId === state.annotationId);
  const isChecked = currentAnnotation?.isChecked || false;

  const toggleCheckStatus = async () => {
    if (!state.annotationId) return;
    try {
      const newStatus = !isChecked;
      await fetch(buildApiUrl(`/api/annotations/${state.annotationId}/check`), {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          isChecked: newStatus,
          checkerName: newStatus ? (state.currentAnnotatorName || state.annotatorName || '') : '',
        }),
      });
      queryClient.invalidateQueries({ queryKey: ['annotations'] });
    } catch (err) {
      console.error("Failed to toggle check status:", err);
    }
  };

  const activeAtlas = availableAtlases.find(a => a.id === state.atlasId);
  const activeAtlasName = activeAtlas 
    ? (lang === 'cs' ? activeAtlas.nazev_cs : activeAtlas.nazev_en)
    : (state.atlasId ? state.atlasId : t('noAtlasSelected'));

  const handleAtlasChange = async (newAtlasId) => {
    if (newAtlasId === state.atlasId) {
      setShowPicker(false);
      return;
    }

    if (state.isDirty) {
      const shouldChangeAtlas = await confirm({
        title: t('dialogConfirmTitle'),
        message: t('confirmAtlasChange'),
        tone: 'warning',
        confirmLabel: t('dialogChangeAtlasAction'),
      });
      if (!shouldChangeAtlas) return;
    }

    if (actions.ensureWritableAnnotation) {
      actions.ensureWritableAnnotation();
    }

    actions.setAtlasId(newAtlasId);
    if (actions.setAnnotationId) actions.setAnnotationId(null);
    setShowPicker(false);
    
    if (actions.handleResetForm) await actions.handleResetForm(true);
  };

  const isNameTaken = !isExistingAnnotation &&
    state.annotatorName.trim() !== "" &&
    annotations.some(entry => {
      const historicName = entry.annotator || entry.annotatorName;
      const historicHash = entry.fileHash || entry.file_hash;
      const historicAtlasId = entry.atlasId || entry.atlas_id;
      return historicHash === state.fileHash &&
        historicAtlasId === state.atlasId &&
        historicName?.toLowerCase().trim() === state.annotatorName.toLowerCase().trim();
    });

  const isSaveDisabled = !state.modelUrl || state.isSaving || !state.annotatorName.trim() || isNameTaken || !state.atlasId;

  return (
    <aside
      className="border-l bg-white flex flex-col h-full shadow-xl shrink-0 relative overflow-visible min-w-0"
      style={{ width: `${width}px`, minWidth: '860px' }}
    >
      <div onMouseDown={onResizeStart} className="absolute top-0 left-0 w-1.5 h-full cursor-col-resize z-50 transition-colors hover:bg-blue-500/30 group">
        <div className="absolute inset-y-0 left-0 w-[1px] bg-slate-200 group-hover:bg-blue-500 transition-colors" />
      </div>

      <AppHeader
        currentModelName={state.modelName}
        onLoadModel={actions.loadModelFromModel}
        currentModelId={state.fileHash}
      />

      {state.modelUrl && (
        <div className="shrink-0 flex flex-col">
          <div className="relative border-b overflow-visible">
            <button 
              onClick={() => setShowPicker(!showPicker)}
              className={`w-full px-4 py-3 flex items-center justify-between transition-colors ${!state.atlasId ? 'bg-rose-50 hover:bg-rose-100' : 'bg-slate-50 hover:bg-slate-100'}`}
            >
              <div className="flex items-center gap-2.5 overflow-hidden">
                <div className={`p-1.5 rounded-lg ${!state.atlasId ? 'bg-rose-100 text-rose-600' : 'bg-blue-100 text-blue-600'}`}>
                  <BookOpen className="w-4 h-4" />
                </div>
                <div className="flex flex-col items-start overflow-hidden">
                  <span className="text-[9px] uppercase tracking-widest text-slate-400 font-bold leading-none mb-1">{t('methodology')}</span>
                  <span className={`text-sm font-bold truncate ${!state.atlasId ? 'text-rose-600' : 'text-slate-900'}`}>
                    {activeAtlasName}
                  </span>
                </div>
              </div>
              <div className="flex items-center gap-2 text-slate-400">
                {!state.atlasId && <span className="text-[10px] font-black text-rose-500 uppercase animate-pulse">{t('selectRequired')}</span>}
                <ChevronDown size={16} className={`transition-transform duration-300 ${showPicker ? 'rotate-180' : ''}`} />
              </div>
            </button>

            {showPicker && (
              <div className="absolute top-full left-0 w-full bg-white shadow-2xl z-[100] border-b animate-in slide-in-from-top-2 duration-200">
                <div className="p-2 max-h-64 overflow-y-auto">
                  <div className="px-3 py-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest border-b mb-1">{t('availableAtlases')}</div>
                  {availableAtlases.map(atlas => (
                    <button
                      key={atlas.id}
                      onClick={() => handleAtlasChange(atlas.id)}
                      className={`w-full text-left px-4 py-3 rounded-xl mb-1 flex items-center justify-between transition-all ${
                        state.atlasId === atlas.id ? 'bg-blue-600 text-white shadow-md' : 'hover:bg-slate-100 text-slate-700'
                      }`}
                    >
                      <span className="font-bold text-sm">{lang === 'cs' ? atlas.nazev_cs : atlas.nazev_en}</span>
                      {state.atlasId === atlas.id && <CheckCircle2 size={16} />}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {state.isForeignAnnotation && (
            <div className="border-b border-amber-100 bg-amber-50 px-3 py-2">
              <div className="flex items-start gap-2 text-amber-800">
                <div className="mt-0.5 rounded-md bg-amber-100 p-1">
                  <AlertCircle className="h-3.5 w-3.5" />
                </div>
                <div className="min-w-0">
                  <p className="text-xs leading-snug text-amber-900">
                    <span className="mr-1 font-black uppercase tracking-wide text-amber-700">
                      {t('foreignAnnotationNoticeTitle')}
                    </span>
                    <span>{t('foreignAnnotationNoticeBody')}</span>
                  </p>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      <div className="flex-1 min-h-0 h-0 w-full relative bg-slate-50/30">
        {!state.atlasId && state.modelUrl ? (
          <div className="h-full flex flex-col items-center justify-center p-10 text-center">
            <div className="w-20 h-20 bg-rose-100 text-rose-600 rounded-[32px] flex items-center justify-center mb-6 shadow-inner">
               <AlertCircle size={40} />
            </div>
            <h3 className="text-xl font-black text-slate-800 mb-2">{t('noAtlasTitle')}</h3>
            <p className="text-slate-500 text-sm mb-8 leading-relaxed">{t('noAtlasDesc')}</p>
            <button 
              onClick={() => setShowPicker(true)}
              className="bg-blue-600 text-white font-black px-8 py-4 rounded-2xl shadow-xl hover:bg-blue-700 transition-all flex items-center gap-3"
            >
              <BookOpen size={20} /> {t('selectAtlasNow')}
            </button>
          </div>
        ) : (
          <ScrollArea className="h-full w-full">
            <div className="p-3 pb-6">
              <Form 
                atlasId={state.atlasId} 
                data={state.formValues} 
                onChange={actions.handleInputChange} 
                disabled={!state.modelUrl}
              />
            </div>
          </ScrollArea>
        )}
      </div>

      {state.modelUrl && isNameTaken && (
        <div className="border-t border-rose-100 bg-rose-50 px-4 py-3 shrink-0">
          <div className="flex items-center gap-2 text-[11px] font-bold text-rose-600 animate-in fade-in slide-in-from-top-1">
            <UserX size={14} />
            <span>{t('nameTaken')}</span>
          </div>
        </div>
      )}

      <div className="shrink-0 bg-white z-20">
        <AppFooter
          onSave={actions.handleSaveToDB}
          onReset={actions.handleResetForm}
          disabled={isSaveDisabled}
          isDirty={state.isDirty}
          isSaving={state.isSaving}
          isChecked={isChecked}
          onToggleCheck={state.annotationId ? toggleCheckStatus : undefined}
        />
      </div>
    </aside>
  );
}