'use client';

import { useState, useEffect, useCallback } from 'react';
import { BookText, Plus, Loader2, Lock, Check, AlertCircle } from 'lucide-react';
import { API_BASE } from '@/lib/config';
import { useI18n } from '@/lib/i18n';
import { cn } from '@/lib/utils';
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;
  glossaryId: string | null;
  onChange: (id: string | null) => void;
  disabled?: boolean;
}

export function GlossarySelector({ sourceLang, targetLang, isPro, glossaryId, onChange, disabled }: GlossarySelectorProps) {
  const { t } = useI18n();
  const [glossaries, setGlossaries] = useState<GlossaryOption[]>([]);
  const [templates, setTemplates] = useState<TemplateOption[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [importingId, setImportingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  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);
    }
  }, []);

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

  const handleImportTemplate = async (template: TemplateOption) => {
    // If a glossary with this template's name already exists, just select it
    const existing = glossaries.find(
      g => g.name.toLowerCase().includes(template.name.toLowerCase().split('/')[0].trim())
    );
    if (existing) {
      onChange(existing.id);
      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(); // Refresh glossary list
        if (newId) onChange(newId);
      } else {
        const errData = await res.json().catch(() => null);
        setError(errData?.message || `Import failed (${res.status})`);
      }
    } catch (e) {
      setError('Network error');
    } finally {
      setImportingId(null);
    }
  };

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

  const filteredGlossaries = sourceLang === 'auto'
    ? glossaries
    : glossaries.filter(g => g.source_language === sourceLang);

  const selected = glossaries.find(g => g.id === glossaryId);

  return (
    <div className="space-y-4">
      <label className="text-[9px] font-black text-brand-dark/40 dark:text-white/40 uppercase tracking-[0.2em] block">
        <BookText size={10} className="inline mr-1.5 text-brand-accent" />
        {t('translate.glossary.title')} <span className="normal-case tracking-normal font-normal text-brand-dark/25 dark:text-white/25">({sourceFlag}→{targetFlag})</span>
      </label>

      {!isPro ? (
        <div className="px-5 py-4 bg-brand-muted/50 dark:bg-white/5 rounded-2xl border border-black/5 dark:border-white/10 flex items-center gap-3 opacity-70">
          <Lock size={12} className="text-brand-dark/30 dark:text-white/30" />
          <span className="text-[10px] font-bold text-brand-dark/40 dark:text-white/40">
            {t('translate.glossary.proOnly')}
          </span>
          <span className="ml-auto px-2 py-0.5 bg-brand-accent/10 text-brand-accent text-[8px] font-black uppercase tracking-widest rounded">
            Pro
          </span>
        </div>
      ) : (
        <div className="space-y-3">
          {/* Error */}
          {error && (
            <div className="px-4 py-3 bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800/30 rounded-xl flex items-center gap-2">
              <AlertCircle size={12} className="text-red-500 shrink-0" />
              <span className="text-[10px] text-red-600 dark:text-red-400">{error}</span>
            </div>
          )}

          {/* My glossaries */}
          {!isLoading && filteredGlossaries.length > 0 && (
            <div className="space-y-1">
              <span className="text-[8px] font-black text-brand-dark/25 dark:text-white/25 uppercase tracking-[0.2em] pl-1">
                {t('translate.glossary.myGlossaries') || 'Mes glossaires'}
              </span>
              {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}
                    onClick={() => onChange(isSelected ? null : g.id)}
                    disabled={disabled}
                    className={cn(
                      "w-full px-4 py-3.5 text-left rounded-xl transition-all flex items-center gap-3",
                      isSelected
                        ? "bg-brand-accent/10 border-2 border-brand-accent/30 shadow-sm"
                        : "bg-brand-muted/50 dark:bg-white/5 border-2 border-transparent hover:border-brand-accent/15 hover:bg-brand-accent/5",
                      disabled && "opacity-50 cursor-not-allowed"
                    )}
                  >
                    {isSelected ? (
                      <div className="w-5 h-5 rounded-full bg-brand-accent flex items-center justify-center shrink-0">
                        <Check size={11} className="text-white" />
                      </div>
                    ) : (
                      <span className="text-sm">{flag}</span>
                    )}
                    <div className="min-w-0 flex-1">
                      <div className={cn(
                        "text-[11px] font-bold truncate",
                        isSelected ? "text-brand-accent" : "text-brand-dark/70 dark:text-white/70"
                      )}>
                        {g.name}
                      </div>
                      <div className="text-[9px] text-brand-dark/30 dark:text-white/30 font-normal normal-case">
                        {g.terms_count} {t('translate.glossary.terms')}
                      </div>
                    </div>
                    {isSelected && (
                      <span className="text-[10px] text-brand-accent/50 hover:text-brand-accent font-bold">✕</span>
                    )}
                  </button>
                );
              })}
            </div>
          )}

          {/* Also show selected glossary if filtered out */}
          {selected && !filteredGlossaries.find(g => g.id === selected.id) && (
            <div className="space-y-1">
              <span className="text-[8px] font-black text-brand-dark/25 dark:text-white/25 uppercase tracking-[0.2em] pl-1">
                {t('translate.glossary.myGlossaries') || 'Mes glossaires'}
              </span>
              <button
                onClick={() => onChange(null)}
                disabled={disabled}
                className="w-full px-4 py-3.5 text-left rounded-xl transition-all flex items-center gap-3 bg-brand-accent/10 border-2 border-brand-accent/30 shadow-sm"
              >
                <div className="w-5 h-5 rounded-full bg-brand-accent flex items-center justify-center shrink-0">
                  <Check size={11} className="text-white" />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="text-[11px] font-bold truncate text-brand-accent">{selected.name}</div>
                  <div className="text-[9px] text-brand-dark/30 dark:text-white/30 font-normal normal-case">
                    {selected.terms_count} {t('translate.glossary.terms')}
                  </div>
                </div>
                <span className="text-[10px] text-brand-accent/50 hover:text-brand-accent font-bold">✕</span>
              </button>
            </div>
          )}

          {/* Templates */}
          {!isLoading && templates.length > 0 && (
            <div className="space-y-2 pt-2 border-t border-black/5 dark:border-white/5">
              <span className="text-[8px] font-black text-brand-dark/25 dark:text-white/25 uppercase tracking-[0.2em] pl-1">
                {t('translate.glossary.fromTemplate') || 'Créer depuis un template'}
              </span>
              <div className="grid grid-cols-2 gap-2">
                {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}
                      onClick={() => {
                        if (existingGlossary) {
                          onChange(isAlreadySelected ? null : existingGlossary.id);
                        } else if (!isImporting) {
                          handleImportTemplate(tmpl);
                        }
                      }}
                      disabled={disabled || isImporting}
                      className={cn(
                        "px-3 py-2.5 text-left rounded-xl transition-all flex items-center gap-2 border",
                        isAlreadySelected
                          ? "bg-brand-accent/10 border-brand-accent/30"
                          : existingGlossary
                          ? "bg-brand-muted/30 dark:bg-white/5 border-black/5 dark:border-white/5 hover:border-brand-accent/20 hover:bg-brand-accent/5"
                          : isImporting
                          ? "bg-brand-accent/5 border-brand-accent/20"
                          : "bg-brand-muted/50 dark:bg-white/5 border-transparent hover:border-brand-accent/20 hover:bg-brand-accent/5",
                        disabled && "opacity-50 cursor-not-allowed"
                      )}
                    >
                      {isImporting ? (
                        <Loader2 size={12} className="text-brand-accent animate-spin shrink-0" />
                      ) : isAlreadySelected ? (
                        <div className="w-4 h-4 rounded-full bg-brand-accent flex items-center justify-center shrink-0">
                          <Check size={9} className="text-white" />
                        </div>
                      ) : existingGlossary ? (
                        <Check size={12} className="text-brand-dark/30 dark:text-white/30 shrink-0" />
                      ) : (
                        <Plus size={12} className="text-brand-accent shrink-0" />
                      )}
                      <span className={cn(
                        "text-[9px] font-black uppercase tracking-widest truncate",
                        isAlreadySelected ? "text-brand-accent" : "text-brand-dark/50 dark:text-white/50"
                      )}>
                        {tmpl.name.split('/')[0].trim()}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* Loading */}
          {isLoading && (
            <div className="flex items-center gap-2 px-4 py-3 text-[10px] text-brand-dark/30 dark:text-white/30">
              <Loader2 size={12} className="animate-spin" />
              {t('translate.glossary.loading') || 'Chargement...'}
            </div>
          )}

          {/* Empty */}
          {!isLoading && filteredGlossaries.length === 0 && !selected && (
            <p className="text-[10px] text-brand-dark/25 dark:text-white/25 pl-1 italic">
              {sourceLang !== 'auto'
                ? `${t('translate.glossary.noGlossaryForPair') || 'Aucun glossaire pour'} ${sourceFlag}→${targetFlag}`
                : (t('translate.glossary.noGlossaries') || 'Aucun glossaire')
              }
            </p>
          )}
        </div>
      )}
    </div>
  );
}
