'use client';

import { useState, useCallback, useRef, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Download, Upload } from 'lucide-react';
import { TermEditor } from './TermEditor';
import { exportGlossaryToCsv, parseCsvToTerms } from './csvUtils';
import { useToast } from '@/components/ui/toast';
import type { Glossary, GlossaryTermInput } from './types';
import { MAX_TERMS_PER_GLOSSARY, SUPPORTED_LANGUAGES } from './types';
import { useI18n } from '@/lib/i18n';

interface EditGlossaryDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  glossary: Glossary | null;
  onSave: (id: string, data: { name: string; source_language: string; target_language: string; terms: GlossaryTermInput[] }) => Promise<void>;
  isSaving: boolean;
}

/** Get the display target for a term based on the selected target language */
function getDisplayTarget(term: { target: string; translations?: Record<string, string> }, lang: string): string {
  if (lang === 'multi' || lang === 'en') return term.target;
  const translations = term.translations || {};
  return translations[lang] || term.target;
}

export function EditGlossaryDialog({
  open,
  onOpenChange,
  glossary,
  onSave,
  isSaving,
}: EditGlossaryDialogProps) {
  const { t } = useI18n();
  const [name, setName] = useState('');
  const [sourceLanguage, setSourceLanguage] = useState('fr');
  const [targetLanguage, setTargetLanguage] = useState('multi');
  const [terms, setTerms] = useState<GlossaryTermInput[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const isInitialized = useRef(false);

  // Initialize when glossary changes
  if (glossary && !isInitialized.current) {
    setName(glossary.name);
    setSourceLanguage(glossary.source_language || 'fr');
    setTargetLanguage(glossary.target_language || 'multi');
    // Store terms with full translations data
    setTerms(glossary.terms.map(t => ({
      source: t.source,
      target: t.target,
      translations: t.translations || {},
    })));
    isInitialized.current = true;
  }

  if (!open && isInitialized.current) {
    isInitialized.current = false;
  }

  // When target language changes, remap displayed targets from translations dict
  const handleTargetLanguageChange = useCallback((newLang: string) => {
    setTargetLanguage(newLang);
    // Don't remap if multi or en — those use the default target field
    if (newLang === 'multi' || newLang === 'en') return;
    setTerms(prev => prev.map(t => {
      const translations = (t as any).translations || {};
      const langTarget = translations[newLang];
      if (langTarget) {
        // Show the language-specific translation as the target
        return { source: t.source, target: langTarget, translations };
      }
      // No translation for this language — keep the default English target
      return t;
    }));
  }, []);

  const handleSave = useCallback(async () => {
    if (!glossary || !name.trim()) return;

    const validTerms = terms.filter(t => t.source.trim() && t.target.trim());

    await onSave(glossary.id, {
      name: name.trim(),
      source_language: sourceLanguage,
      target_language: targetLanguage,
      terms: validTerms,
    });
  }, [glossary, name, sourceLanguage, targetLanguage, terms, onSave]);

  const handleExport = useCallback(() => {
    if (!glossary) return;

    const glossaryWithCurrentTerms: Glossary = {
      ...glossary,
      name,
      terms: terms.map((t, i) => ({
        id: `temp-${i}`,
        source: t.source,
        target: t.target,
        translations: (t as any).translations || {},
        created_at: null,
      })),
    };

    exportGlossaryToCsv(glossaryWithCurrentTerms);
  }, [glossary, name, terms]);

  const handleImportClick = useCallback(() => {
    fileInputRef.current?.click();
  }, []);

  const { toast } = useToast();

  const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (event) => {
      const text = event.target?.result;
      if (typeof text === 'string') {
        const importedTerms = parseCsvToTerms(text);
        if (importedTerms.length > 0) {
          if (importedTerms.length > MAX_TERMS_PER_GLOSSARY) {
            toast({
              variant: 'destructive',
              title: t('glossaries.edit.importFailedTitle'),
              description: t('glossaries.edit.importFailedMaxDesc', { count: importedTerms.length, max: MAX_TERMS_PER_GLOSSARY }),
            });
            e.target.value = '';
            return;
          }
          setTerms(importedTerms);
          toast({
            title: t('glossaries.edit.importSuccessTitle'),
            description: t('glossaries.edit.importSuccessDesc', { count: importedTerms.length }),
          });
        } else {
          toast({
            variant: 'destructive',
            title: t('glossaries.edit.importFailedTitle'),
            description: t('glossaries.edit.importFailedEmptyDesc'),
          });
        }
      }
    };
    reader.onerror = () => {
      toast({
        variant: 'destructive',
        title: t('glossaries.edit.importFailedTitle'),
        description: t('glossaries.edit.importFailedReadDesc'),
      });
    };
    reader.readAsText(file);

    e.target.value = '';
  }, [toast]);

  const validTermsCount = terms.filter(t => t.source.trim() && t.target.trim()).length;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{t('glossaries.edit.title')}</DialogTitle>
          <DialogDescription>
            {t('glossaries.edit.description')}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          <div className="space-y-2">
            <Label htmlFor="glossary-name">{t('glossaries.edit.nameLabel')}</Label>
            <Input
              id="glossary-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t('glossaries.edit.namePlaceholder')}
              disabled={isSaving}
            />
          </div>

          <div className="flex items-center gap-2">
            <div className="flex-1">
              <Label className="text-xs text-muted-foreground mb-1 block">{t('glossaries.edit.sourceLang')}</Label>
              <select
                value={sourceLanguage}
                onChange={e => setSourceLanguage(e.target.value)}
                disabled={isSaving}
                className="w-full h-9 rounded-md border border-input bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              >
                {SUPPORTED_LANGUAGES.filter(l => l.code !== 'multi').map(l => (
                  <option key={l.code} value={l.code}>{l.flag} {l.label}</option>
                ))}
              </select>
            </div>
            <div className="pt-5 text-muted-foreground font-bold">→</div>
            <div className="flex-1">
              <Label className="text-xs text-muted-foreground mb-1 block">{t('glossaries.edit.targetLang')}</Label>
              <select
                value={targetLanguage}
                onChange={e => handleTargetLanguageChange(e.target.value)}
                disabled={isSaving}
                className="w-full h-9 rounded-md border border-input bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              >
                {SUPPORTED_LANGUAGES.map(l => (
                  <option key={l.code} value={l.code}>{l.flag} {l.label}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="space-y-2">
            <Label>{t('glossaries.edit.termsLabel', { count: validTermsCount })}</Label>
            <TermEditor
              terms={terms}
              onChange={setTerms}
              disabled={isSaving}
            />
          </div>

          <div className="flex items-center gap-2 pt-2">
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={handleExport}
              disabled={isSaving || validTermsCount === 0}
              className="gap-1.5"
            >
              <Download className="size-3.5" />
              {t('glossaries.edit.exportCsv')}
            </Button>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={handleImportClick}
              disabled={isSaving}
              className="gap-1.5"
            >
              <Upload className="size-3.5" />
              {t('glossaries.edit.importCsv')}
            </Button>
            <input
              ref={fileInputRef}
              type="file"
              accept=".csv"
              onChange={handleFileChange}
              className="hidden"
            />
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isSaving}
          >
            {t('glossaries.edit.cancel')}
          </Button>
          <Button
            onClick={handleSave}
            disabled={isSaving || !name.trim()}
          >
            {isSaving ? t('glossaries.edit.saving') : t('glossaries.edit.saveChanges')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
