/**
 * AppHeader
 * Displays the current model identity and provides quick switching to other
 * stored models loaded from the backend model catalog.
 */
import React, { useState } from 'react';
import { FileCode2, FolderOpen, ChevronDown, Check, Loader2 } from 'lucide-react';
import { useLanguage } from '@/context/LanguageContext';
import { useQuery } from '@tanstack/react-query';
import { useMessageDialog } from '../../hooks/useMessageDialog';
import { buildApiUrl } from '../../utils/api';

export default function AppHeader({ 
  currentModelName, 
  onLoadModel,
  currentModelId
}) {
  const { t } = useLanguage();
  const { confirm } = useMessageDialog();
  const [isModelsDropdownOpen, setIsModelsDropdownOpen] = useState(false);

  const { data: allModels, isLoading: modelsLoading } = useQuery({
    queryKey: ['models'],
    queryFn: async () => {
      const r = await fetch(buildApiUrl('/api/models'));
      if (!r.ok) throw new Error('Failed to load models');
      return r.json();
    },
  });

  const handleModelSelect = async (model) => {
    if (model.id === currentModelId) {
      return;
    }

    const modelName = model.external_id;
    const shouldLoadModel = await confirm({
      title: t('dialogConfirmTitle'),
      message: t('confirmLoadModel').replace('{model}', modelName),
      tone: 'warning',
      confirmLabel: t('dialogLoadAction'),
    });
    if (shouldLoadModel) {
      onLoadModel(model);
      setIsModelsDropdownOpen(false);
    }
  };

  const handleChooseModel = () => {
    setIsModelsDropdownOpen(!isModelsDropdownOpen);
  };

  return (
    <header className="p-2 border-b shrink-0 bg-white">
      <div className="flex items-center justify-between p-2 rounded-xl bg-slate-50 border border-slate-200">
        <div className="flex-1 mx-4 text-center">
          {currentModelName ? (
            <div className="flex items-center justify-center gap-2 text-blue-700 font-bold">
              <FileCode2 size={16} className="shrink-0 text-blue-500" />
              <span className="text-sm truncate">{currentModelName}</span>
            </div>
          ) : (
            <span className="text-sm text-slate-400 italic">{t('noModelLoaded')}</span>
          )}
        </div>

        <div className="relative">
          <button
            onClick={handleChooseModel}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-all shadow-sm font-medium"
            title={t('chooseNewModel')}
          >
            <FolderOpen size={16} />
            <span className="text-xs font-bold uppercase tracking-wider">{t('chooseNewModel')}</span>
            <ChevronDown size={14} />
          </button>

          {isModelsDropdownOpen && (
            <div className="absolute top-full right-0 mt-1 w-80 bg-white border border-slate-200 rounded-lg shadow-lg z-50 max-h-96 overflow-y-auto">
              {modelsLoading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="animate-spin text-blue-600" size={20} />
                  <span className="ml-2 text-sm text-slate-600">{t('loadingModels')}</span>
                </div>
              ) : allModels && allModels.length > 0 ? (
                <div className="py-1">
                  {allModels.map((model) => (
                    <button
                      key={model.id}
                      onClick={() => handleModelSelect(model)}
                      className={`w-full text-left px-4 py-3 hover:bg-slate-50 transition-colors flex items-center justify-between ${
                        model.id === currentModelId ? 'bg-blue-50 text-blue-700' : 'text-slate-700'
                      }`}
                    >
                      <div className="flex flex-col items-start">
                        <div className="flex items-center gap-2 truncate w-full">
                          <FileCode2 size={14} className="shrink-0" />
                          <span className="text-sm truncate font-medium">{model.external_id}</span>
                        </div>
                        <div className="flex items-center gap-2 text-xs text-slate-500 mt-1">
                          <span>{new Date(model.created_at).toLocaleDateString()}</span>
                          {model.has_annotations && (
                            <span className="bg-green-100 text-green-700 px-2 py-0.5 rounded-full">
                              {t('hasAnnotations')}
                            </span>
                          )}
                        </div>
                      </div>
                      {model.id === currentModelId && <Check size={14} className="shrink-0 text-blue-600" />}
                    </button>
                  ))}
                </div>
              ) : (
                <div className="py-8 text-center text-slate-500">
                  <p className="text-sm">{t('noModelsAvailable')}</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {isModelsDropdownOpen && (
        <div 
          className="fixed inset-0 z-40" 
          onClick={() => setIsModelsDropdownOpen(false)}
        />
      )}
    </header>
  );
}