'use client';

import { useState, useCallback } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { TermEditor } from './TermEditor';
import type { GlossaryTermInput } from './types';
import { useI18n } from '@/lib/i18n';
import { Loader2, PenLine } from 'lucide-react';
import { SUPPORTED_LANGUAGES } from './types';

interface CreateGlossaryDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onCreate: (data: { name: string; source_language: string; target_language: string; terms: GlossaryTermInput[] }) => Promise<void>;
  isCreating: boolean;
}

export function CreateGlossaryDialog({
  open,
  onOpenChange,
  onCreate,
  isCreating,
}: CreateGlossaryDialogProps) {
  const { t } = useI18n();
  const [name, setName] = useState('');
  const [sourceLanguage, setSourceLanguage] = useState('fr');
  const [targetLanguage, setTargetLanguage] = useState('multi');
  const [terms, setTerms] = useState<GlossaryTermInput[]>([{ source: '', target: '' }]);

  const reset = useCallback(() => {
    setName('');
    setSourceLanguage('fr');
    setTargetLanguage('multi');
    setTerms([{ source: '', target: '' }]);
  }, []);

  const handleOpenChange = useCallback((newOpen: boolean) => {
    if (!newOpen) reset();
    onOpenChange(newOpen);
  }, [onOpenChange, reset]);

  const handleSubmit = useCallback(async () => {
    if (!name.trim()) return;
    const termsToSave = terms.filter(t => t.source.trim() && t.target.trim());
    await onCreate({ name: name.trim(), source_language: sourceLanguage, target_language: targetLanguage, terms: termsToSave });
    reset();
  }, [name, terms, sourceLanguage, targetLanguage, onCreate, reset]);

  const canSubmit = !!(name.trim() && !isCreating && terms.some(t => t.source.trim() && t.target.trim()));

  const validTermsCount = terms.filter(t => t.source.trim() && t.target.trim()).length;
  const submitLabel = isCreating
    ? t('glossaries.dialog.creating') || 'Création…'
    : validTermsCount > 0
    ? t('glossaries.dialog.createBtn', { count: String(validTermsCount) }) || `Créer (${validTermsCount})`
    : t('glossaries.dialog.createEmpty') || 'Créer vide';

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-2xl max-h-[90vh] flex flex-col overflow-hidden !rounded-2xl border-black/5 dark:border-white/5 bg-white dark:bg-[#141414] shadow-editorial p-0">
        <DialogHeader className="shrink-0 px-8 pt-8 pb-0">
          <DialogTitle className="text-2xl font-serif font-medium text-brand-dark dark:text-white tracking-tight">
            {t('glossaries.dialog.title') || 'Nouveau glossaire'}
          </DialogTitle>
          <DialogDescription className="text-[11px] text-brand-dark/45 dark:text-white/40 font-light">
            {t('glossaries.dialog.description') || 'Créez un glossaire pour vos traductions'}
          </DialogDescription>
        </DialogHeader>

        <div className="shrink-0 space-y-4 px-8 pt-5">
          <div>
            <Label htmlFor="glossary-name" className="text-xs font-bold text-brand-dark/70 dark:text-white/60 uppercase tracking-wider">
              {t('glossaries.dialog.nameLabel') || 'Nom'}
            </Label>
            <Input
              id="glossary-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t('glossaries.dialog.namePlaceholder') || 'Mon glossaire'}
              disabled={isCreating}
              className="mt-1.5 bg-brand-muted/30 dark:bg-white/[0.03] border-black/5 dark:border-white/10 rounded-xl focus:ring-brand-accent/20 focus:border-brand-accent/30"
            />
          </div>

          <div className="flex items-center gap-3">
            <div className="flex-1">
              <Label htmlFor="glossary-source-lang" className="text-[10px] font-bold text-brand-dark/50 dark:text-white/40 uppercase tracking-wider mb-1.5 block">
                {t('glossaries.edit.sourceLang') || 'Langue source'}
              </Label>
              <select
                id="glossary-source-lang"
                value={sourceLanguage}
                onChange={e => setSourceLanguage(e.target.value)}
                disabled={isCreating}
                className="w-full h-10 rounded-xl border border-black/5 dark:border-white/10 bg-brand-muted/30 dark:bg-white/[0.03] px-3 text-sm text-brand-dark dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-accent/20 focus:border-brand-accent/30 transition-all"
              >
                {SUPPORTED_LANGUAGES.map(l => (
                  <option key={l.code} value={l.code}>{l.flag} {l.label}</option>
                ))}
              </select>
            </div>
            <div className="pt-5 text-brand-accent font-bold text-lg">→</div>
            <div className="flex-1">
              <Label htmlFor="glossary-target-lang" className="text-[10px] font-bold text-brand-dark/50 dark:text-white/40 uppercase tracking-wider mb-1.5 block">
                {t('glossaries.edit.targetLang') || 'Langue cible'}
              </Label>
              <select
                id="glossary-target-lang"
                value={targetLanguage}
                onChange={e => setTargetLanguage(e.target.value)}
                disabled={isCreating}
                className="w-full h-10 rounded-xl border border-black/5 dark:border-white/10 bg-brand-muted/30 dark:bg-white/[0.03] px-3 text-sm text-brand-dark dark:text-white focus:outline-none focus:ring-2 focus:ring-brand-accent/20 focus:border-brand-accent/30 transition-all"
              >
                {SUPPORTED_LANGUAGES.map(l => (
                  <option key={l.code} value={l.code}>{l.flag} {l.label}</option>
                ))}
              </select>
            </div>
          </div>
        </div>

        <div className="flex-1 overflow-y-auto px-8 pt-5 min-h-0">
          <div className="flex items-center gap-1.5 mb-3 text-brand-accent">
            <PenLine className="size-3.5" />
            <span className="text-xs font-bold uppercase tracking-wider">
              {t('glossaries.dialog.tabManual') || 'Saisie manuelle'}
            </span>
          </div>
          <TermEditor
            terms={terms}
            onChange={setTerms}
            disabled={isCreating}
          />
        </div>

        <div className="shrink-0 px-8 py-5 border-t border-black/5 dark:border-white/5 flex justify-end gap-3">
          <button
            type="button"
            onClick={() => handleOpenChange(false)}
            disabled={isCreating}
            className="px-5 py-2.5 bg-brand-muted dark:bg-white/5 text-brand-dark/50 dark:text-white/40 rounded-xl text-[11px] font-bold uppercase tracking-wider hover:text-brand-dark dark:hover:text-white transition-all cursor-pointer disabled:opacity-50"
          >
            {t('glossaries.dialog.cancel') || 'Annuler'}
          </button>
          <button
            type="button"
            onClick={handleSubmit}
            disabled={!canSubmit}
            className="premium-button px-8 py-2.5 text-[11px] uppercase tracking-widest !rounded-xl flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-bold"
          >
            {isCreating && <Loader2 className="size-3.5 animate-spin" />}
            {submitLabel}
          </button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
