'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { BookOpen, Plus, Loader2, Check, ChevronDown, X, Globe, ChevronRight } from 'lucide-react';
import { API_BASE } from '@/lib/config';
import { useI18n } from '@/lib/i18n';
import { cn } from '@/lib/utils';
import { Switch } from '@/components/ui/switch';
import { SUPPORTED_LANGUAGES } from '../glossaries/types';

interface GlossaryOption {
  id: string;
  name: string;
  source_language: string;
  terms_count: number;
}

interface TemplateOption {
  id: string;
  name: string;
  description: string;
  source_lang: string;
  target_lang: string;
  terms_count: number;
}

interface GlossarySelectorProps {
  sourceLang: string;
  targetLang: string;
  isPro: boolean;
  mode: string;
  glossaryId: string | null;
  onChange: (id: string | null) => void;
  disabled?: boolean;
}

export function GlossarySelector({ sourceLang, targetLang, isPro, mode, glossaryId, onChange, disabled }: GlossarySelectorProps) {
  const { t } = useI18n();
  const [glossaries, setGlossaries] = useState<GlossaryOption[]>([]);
  const [templates, setTemplates] = useState<TemplateOption[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isGlossaryEnabled, setIsGlossaryEnabled] = useState(!!glossaryId);
  const [selectedGlossaryDetail, setSelectedGlossaryDetail] = useState<any>(null);
  const [isLoadingDetail, setIsLoadingDetail] = useState(false);
  const [importingId, setImportingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isOpen, setIsOpen] = useState(false);
  const [showTemplates, setShowTemplates] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  // Form states for adding term
  const [newSource, setNewSource] = useState('');
  const [newTarget, setNewTarget] = useState('');
  const [isAddingTerm, setIsAddingTerm] = useState(false);

  const fetchData = useCallback(async () => {
    try {
      const token = localStorage.getItem('token');
      const headers: Record<string, string> = {};
      if (token) headers['Authorization'] = `Bearer ${token}`;

      const [glossaryRes, templateRes] = await Promise.all([
        fetch(`${API_BASE}/api/v1/glossaries?per_page=100`, { headers }),
        fetch(`${API_BASE}/api/v1/glossaries/templates/list`, { headers }),
      ]);

      if (glossaryRes.ok) {
        const data = await glossaryRes.json();
        setGlossaries(data.data || []);
      }
      if (templateRes.ok) {
        const data = await templateRes.json();
        setTemplates(data.data || []);
      }
    } catch {
      // ignore
    } finally {
      setIsLoading(false);
    }
  }, []);

  const fetchGlossaryDetail = useCallback(async (id: string) => {
    setIsLoadingDetail(true);
    try {
      const token = localStorage.getItem('token');
      const headers: Record<string, string> = {};
      if (token) headers['Authorization'] = `Bearer ${token}`;

      const res = await fetch(`${API_BASE}/api/v1/glossaries/${id}`, { headers });
      if (res.ok) {
        const data = await res.json();
        setSelectedGlossaryDetail(data.data || null);
      }
    } catch {
      // ignore
    } finally {
      setIsLoadingDetail(false);
    }
  }, []);

  useEffect(() => { fetchData(); }, [fetchData]);

  // Synchronize glossary detail and enablement state with props
  useEffect(() => {
    if (glossaryId) {
      setIsGlossaryEnabled(true);
      fetchGlossaryDetail(glossaryId);
    } else {
      setSelectedGlossaryDetail(null);
    }
  }, [glossaryId, fetchGlossaryDetail]);

  // Close dropdown on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    }
    if (isOpen) document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [isOpen]);

  const handleImportTemplate = async (template: TemplateOption) => {
    const existing = glossaries.find(
      g => g.name.toLowerCase().includes(template.name.toLowerCase().split('/')[0].trim())
    );
    if (existing) {
      onChange(existing.id);
      setIsGlossaryEnabled(true);
      setIsOpen(false);
      return;
    }

    const token = localStorage.getItem('token');
    const headers: Record<string, string> = { 'Content-Type': 'application/json' };
    if (token) headers['Authorization'] = `Bearer ${token}`;

    setImportingId(template.id);
    setError(null);
    try {
      const res = await fetch(`${API_BASE}/api/v1/glossaries/import?template_id=${encodeURIComponent(template.id)}`, {
        method: 'POST',
        headers,
      });

      if (res.ok) {
        const data = await res.json();
        const newId = data.data?.id;
        await fetchData();
        if (newId) {
          onChange(newId);
          setIsGlossaryEnabled(true);
        }
        setIsOpen(false);
      } else {
        const errData = await res.json().catch(() => null);
        setError(errData?.message || `Import failed (${res.status})`);
      }
    } catch {
      setError('Network error');
    } finally {
      setImportingId(null);
    }
  };

  const handleAddTerm = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!glossaryId || !newSource.trim() || !newTarget.trim()) return;

    setIsAddingTerm(true);
    setError(null);
    try {
      const token = localStorage.getItem('token');
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
      };
      if (token) headers['Authorization'] = `Bearer ${token}`;

      // Fetch latest terms
      const detailRes = await fetch(`${API_BASE}/api/v1/glossaries/${glossaryId}`, { headers });
      let currentTerms = [];
      if (detailRes.ok) {
        const detailData = await detailRes.json();
        currentTerms = detailData.data?.terms || [];
      }

      const mappedTerms = currentTerms.map((t: any) => ({
        source: t.source,
        target: t.target,
        translations: t.translations || {}
      }));

      // Append
      const updatedTerms = [...mappedTerms, { source: newSource.trim(), target: newTarget.trim(), translations: {} }];

      const res = await fetch(`${API_BASE}/api/v1/glossaries/${glossaryId}`, {
        method: 'PATCH',
        headers,
        body: JSON.stringify({
          terms: updatedTerms
        })
      });

      if (res.ok) {
        setNewSource('');
        setNewTarget('');
        // Refresh details
        fetchGlossaryDetail(glossaryId);
        fetchData();
      } else {
        const errData = await res.json().catch(() => null);
        setError(errData?.message || 'Erreur lors de l\'ajout du terme');
      }
    } catch {
      setError('Erreur réseau');
    } finally {
      setIsAddingTerm(false);
    }
  };

  const sourceFlag = SUPPORTED_LANGUAGES.find(l => l.code === sourceLang)?.flag ?? '';
  const targetFlag = SUPPORTED_LANGUAGES.find(l => l.code === targetLang)?.flag ?? '';

  const filteredGlossaries = glossaries;
  const selected = glossaries.find(g => g.id === glossaryId);
  return (
    <div
      className="bg-brand-muted/30 dark:bg-white/[0.02] border border-black/[0.03] dark:border-white/[0.03] p-4 rounded-xl space-y-3 text-left"
      ref={containerRef}
    >
      <div className="flex justify-between items-center">
        <div className="flex items-center gap-2">
          <BookOpen size={12} className="text-brand-accent shrink-0" />
          <span className="text-[9px] font-black uppercase tracking-[0.1em] text-brand-dark dark:text-white truncate">
            {t('translate.glossary.title') || 'Glossaire & Terminologie'}
          </span>
          <span className="text-[7.5px] text-brand-dark/40 dark:text-white/40 shrink-0 font-medium font-mono">
            ({sourceFlag || 'AUTO'}➔{targetFlag})
          </span>
        </div>

        {/* Active switch slider */}
        {isPro && mode === 'llm' && (
          <button
            type="button"
            disabled={disabled}
            onClick={() => {
              const nextVal = !isGlossaryEnabled;
              setIsGlossaryEnabled(nextVal);
              if (!nextVal) {
                onChange(null);
              } else if (filteredGlossaries.length > 0 && !glossaryId) {
                onChange(filteredGlossaries[0].id);
              }
            }}
            className={cn(
              "w-8 h-4 rounded-full relative transition-colors",
              isGlossaryEnabled ? 'bg-brand-accent' : 'bg-brand-dark/10 dark:bg-white/10',
              disabled && "opacity-50 cursor-not-allowed"
            )}
          >
            <div className={cn(
              "w-3.5 h-3.5 bg-white rounded-full absolute top-0.5 shadow transition-all",
              isGlossaryEnabled ? 'left-[13px]' : 'left-0.5'
            )} />
          </button>
        )}
      </div>

      {mode === 'classic' ? (
        <div className="p-2.5 bg-brand-dark/5 dark:bg-white/5 rounded-lg text-center">
          <span className="text-[7.5px] font-black uppercase opacity-45 block">
            Moteur neutre sans glossaire (IA uniquement)
          </span>
        </div>
      ) : !isPro ? (
        <div className="p-2.5 rounded-lg bg-brand-dark/5 dark:bg-white/5 text-center">
          <p className="text-[7.5px] text-brand-dark/50 dark:text-white/45 leading-relaxed font-light">
            {t('translate.glossary.proOnly') || 'Passez Pro pour appliquer vos glossaires terminologiques.'}
          </p>
        </div>
      ) : isGlossaryEnabled ? (
        <div className="space-y-3 animate-fade-in">
          
          {/* Select Glossary Trigger button */}
          <div className="relative">
            <button
              type="button"
              disabled={disabled}
              onClick={() => setIsOpen(!isOpen)}
              className={cn(
                "w-full bg-white dark:bg-[#1a1a1a] border border-black/5 dark:border-white/5 hover:border-black/10 dark:hover:border-white/10 py-2 px-3 rounded-lg flex items-center justify-between shadow-sm transition-all",
                isOpen && "border-brand-accent dark:border-brand-accent",
                disabled && "opacity-50 cursor-not-allowed"
              )}
            >
              <div className="text-left min-w-0 flex-1 pr-2">
                <span className="text-[9px] font-black text-brand-dark dark:text-white tracking-tight block truncate">
                  {selected ? selected.name : (isLoading ? "Chargement..." : "Sélectionner un glossaire...")}
                </span>
                <span className="text-[7px] font-extrabold uppercase tracking-wider text-brand-dark/40 dark:text-white/40 block mt-0.5">
                  {selected
                    ? `${SUPPORTED_LANGUAGES.find(l => l.code === selected.source_language)?.flag || '🌐'} ➜ ${targetFlag} • ${selected.terms_count} termes`
                    : (filteredGlossaries.length > 0 ? "Aucun glossaire sélectionné" : "Aucun glossaire disponible")
                  }
                </span>
              </div>
              <ChevronDown size={11} className={cn("text-brand-dark/30 dark:text-white/30 shrink-0 transition-transform duration-200", isOpen && "rotate-180")} />
            </button>

            {/* Error message */}
            {error && (
              <p className="text-[7.5px] text-red-500 pl-1 mt-1 font-medium">{error}</p>
            )}

            {/* Selector Dropdown list */}
            {isOpen && !disabled && (
              <div className="absolute top-[102%] left-0 right-0 bg-white dark:bg-[#1a1a1a] border border-black/10 dark:border-white/10 rounded-xl shadow-2xl p-1.5 z-40 max-h-48 overflow-y-auto animate-fade-in">
                {filteredGlossaries.length > 0 ? (
                  filteredGlossaries.map(g => {
                    const flag = SUPPORTED_LANGUAGES.find(l => l.code === g.source_language)?.flag ?? '';
                    const isSelected = g.id === glossaryId;
                    return (
                      <button
                        key={g.id}
                        type="button"
                        onClick={() => {
                          onChange(isSelected ? null : g.id);
                          setIsOpen(false);
                        }}
                        className={cn(
                          "w-full text-left px-3 py-2 rounded-lg transition-colors flex items-center justify-between",
                          isSelected
                            ? 'bg-brand-accent/5 text-brand-accent'
                            : 'hover:bg-brand-muted dark:hover:bg-white/5 text-brand-dark/70 dark:text-white/70'
                        )}
                      >
                        <div className="text-left min-w-0 flex-1 pr-2">
                          <span className="text-[9px] font-black block leading-none truncate">{g.name}</span>
                          <span className="text-[7.5px] uppercase tracking-wider text-brand-dark/40 dark:text-white/40 font-bold block mt-1">
                            {flag || '🌐'} ➜ {targetFlag} • {g.terms_count} termes
                          </span>
                        </div>
                        {isSelected && <Check size={10} className="text-brand-accent shrink-0" />}
                      </button>
                    );
                  })
                ) : (
                  <p className="px-3 py-4 text-[8px] text-brand-dark/40 dark:text-white/30 italic text-center font-light">
                    {sourceLang !== 'auto'
                      ? `Aucun glossaire pour ${sourceFlag}➔${targetFlag}`
                      : "Aucun glossaire disponible"
                    }
                  </p>
                )}
              </div>
            )}
          </div>

          {/* Dynamic Terms Preview block */}
          {selected && (
            <div className="bg-white/80 dark:bg-[#1a1a1a]/40 rounded-lg p-2.5 border border-black/[0.02] dark:border-white/[0.02] space-y-2">
              <div className="flex justify-between items-center border-b border-black/[0.02] dark:border-white/[0.02] pb-1">
                <span className="text-[7.5px] font-black uppercase tracking-wider text-brand-dark/30 dark:text-white/30 block">
                  Aperçu des correspondances actives :
                </span>
                <span className="text-[7px] font-bold text-brand-dark/40 dark:text-white/40">
                  {selectedGlossaryDetail?.terms?.length || selected.terms_count} au total
                </span>
              </div>
              
              {isLoadingDetail ? (
                <div className="flex items-center justify-center py-3 gap-1.5 text-[8px] text-brand-dark/40 dark:text-white/30 font-light">
                  <Loader2 size={10} className="animate-spin text-brand-accent" /> Chargement...
                </div>
              ) : selectedGlossaryDetail?.terms && selectedGlossaryDetail.terms.length > 0 ? (
                <div className="grid grid-cols-1 gap-1 max-h-[105px] overflow-y-auto pr-1">
                  {selectedGlossaryDetail.terms.slice(0, 4).map((t: any, i: number) => (
                    <div key={t.id || i} className="flex justify-between items-center bg-brand-muted/30 dark:bg-white/5 px-2 py-1 rounded-md text-[8px]">
                      <span className="font-extrabold text-brand-dark/75 dark:text-white/70 truncate max-w-[220px]">
                        {t.source} ➔ {t.target}
                      </span>
                      <span className="inline-block w-1.5 h-1.5 bg-brand-accent rounded-full shrink-0" />
                    </div>
                  ))}
                  {selectedGlossaryDetail.terms.length > 4 && (
                    <span className="text-[7px] text-brand-dark/40 dark:text-white/40 block text-right font-medium mt-1">
                      + {selectedGlossaryDetail.terms.length - 4} autres termes
                    </span>
                  )}
                </div>
              ) : (
                <p className="py-3 text-[8px] text-brand-dark/40 dark:text-white/30 italic text-center font-light">Aucun terme dans ce glossaire.</p>
              )}
            </div>
          )}

          {/* Ultra-neat Quick Term Adder */}
          {selected && (
            <form onSubmit={handleAddTerm} className="flex gap-1">
              <input
                type="text"
                required
                placeholder="Terme Source"
                value={newSource}
                onChange={(e) => setNewSource(e.target.value)}
                disabled={isAddingTerm || disabled}
                className="flex-1 bg-white dark:bg-[#1a1a1a] border border-black/5 dark:border-white/5 rounded-lg px-2 py-1 text-[8px] font-semibold text-brand-dark dark:text-white placeholder:text-brand-dark/30 outline-none focus:border-brand-accent"
              />
              <input
                type="text"
                required
                placeholder="Traduction"
                value={newTarget}
                onChange={(e) => setNewTarget(e.target.value)}
                disabled={isAddingTerm || disabled}
                className="flex-1 bg-white dark:bg-[#1a1a1a] border border-black/5 dark:border-white/5 rounded-lg px-2 py-1 text-[8px] font-semibold text-brand-dark dark:text-white placeholder:text-brand-dark/30 outline-none focus:border-brand-accent"
              />
              <button
                type="submit"
                disabled={isAddingTerm || disabled || !newSource.trim() || !newTarget.trim()}
                className="px-2.5 bg-brand-dark dark:bg-white text-white dark:text-brand-dark rounded-lg flex items-center justify-center disabled:opacity-35 transition-colors"
                title="Ajouter le terme"
              >
                {isAddingTerm ? (
                  <Loader2 size={10} className="animate-spin" />
                ) : (
                  <Plus size={10} />
                )}
              </button>
            </form>
          )}

          {/* Interactive Accordion for Templates Generator */}
          {templates.length > 0 && (
            <div className="border-t border-black/[0.03] dark:border-white/[0.03] pt-2 mt-1">
              <button
                type="button"
                onClick={() => setShowTemplates(!showTemplates)}
                className="w-full flex items-center justify-between text-[8px] font-black uppercase tracking-wider text-brand-dark/40 dark:text-white/40 hover:text-brand-dark dark:hover:text-white transition-colors"
              >
                <span>⚡ Créer ou Charger depuis un Template</span>
                <ChevronRight size={10} className={cn("transform transition-transform text-brand-accent", showTemplates ? 'rotate-95' : '')} />
              </button>

              {showTemplates && (
                <div className="grid grid-cols-2 gap-1 mt-2 p-1 bg-white/40 dark:bg-black/10 rounded-lg animate-fade-in max-h-32 overflow-y-auto">
                  {templates.map(tmpl => {
                    const isImporting = importingId === tmpl.id;
                    const existingGlossary = glossaries.find(
                      g => g.name.toLowerCase().includes(tmpl.name.toLowerCase().split('/')[0].trim())
                    );
                    const isAlreadySelected = existingGlossary?.id === glossaryId;

                    return (
                      <button
                        key={tmpl.id}
                        type="button"
                        disabled={isImporting || disabled}
                        onClick={() => {
                          if (existingGlossary) {
                            onChange(isAlreadySelected ? null : existingGlossary.id);
                          } else {
                            handleImportTemplate(tmpl);
                          }
                        }}
                        className={cn(
                          "px-2 py-1 rounded text-left transition-all",
                          isAlreadySelected
                            ? 'bg-brand-accent/10 border-l-2 border-brand-accent'
                            : 'hover:bg-brand-muted dark:hover:bg-white/5'
                        )}
                      >
                        <span className="text-[7.5px] font-extrabold text-brand-dark dark:text-white block truncate leading-none">
                          {isImporting ? 'Importation...' : tmpl.name.split('/')[0].trim()}
                        </span>
                        <span className="text-[6px] tracking-wider font-bold text-brand-dark/30 dark:text-white/30 block leading-tight uppercase">
                          {tmpl.terms_count} termes
                        </span>
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </div>
      ) : (
        <div className="p-2.5 bg-brand-dark/5 dark:bg-white/5 rounded-lg text-center animate-fade-in">
          <span className="text-[7.5px] font-black uppercase opacity-40">Moteur neutre sans glossaire appliqué</span>
        </div>
      )}
    </div>
  );
}
