'use client';

import { useState, useCallback, useRef } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { TermEditor } from './TermEditor';
import { parseFileToTerms } from './csvUtils';
import { useGlossaryTemplates } from './useGlossaries';
import type { GlossaryTermInput } from './types';
import type { GlossaryTemplate } from './useGlossaries';
import { useI18n } from '@/lib/i18n';
import {
  Upload,
  FileText,
  BookOpen,
  PenLine,
  CheckCircle2,
  AlertCircle,
  Loader2,
  X,
  Scale,
  Cpu,
  TrendingUp,
  HeartPulse,
  Megaphone,
  Users,
  FlaskConical,
  ShoppingCart,
} from 'lucide-react';
import { cn } from '@/lib/utils';

interface CreateGlossaryDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onCreate: (data: { name: string; terms: GlossaryTermInput[] }) => Promise<void>;
  onImportTemplate: (templateId: string, name?: string) => Promise<void>;
  isCreating: boolean;
  isImportingTemplate: boolean;
}

const TEMPLATE_ICONS: Record<string, React.ReactNode> = {
  legal: <Scale className="size-5" />,
  technology: <Cpu className="size-5" />,
  finance: <TrendingUp className="size-5" />,
  medical: <HeartPulse className="size-5" />,
  marketing: <Megaphone className="size-5" />,
  hr: <Users className="size-5" />,
  scientific: <FlaskConical className="size-5" />,
  ecommerce: <ShoppingCart className="size-5" />,
};

const TEMPLATE_COLORS: Record<string, string> = {
  legal: 'bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100',
  technology: 'bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100',
  finance: 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100',
  medical: 'bg-red-50 text-red-700 border-red-200 hover:bg-red-100',
  marketing: 'bg-orange-50 text-orange-700 border-orange-200 hover:bg-orange-100',
  hr: 'bg-teal-50 text-teal-700 border-teal-200 hover:bg-teal-100',
  scientific: 'bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100',
  ecommerce: 'bg-pink-50 text-pink-700 border-pink-200 hover:bg-pink-100',
};

type FileStatus = 'idle' | 'parsing' | 'success' | 'error';

const MAX_FILE_SIZE_MB = 5;

function TemplateCard({
  template,
  onSelect,
  isLoading,
  termsLabel,
}: {
  template: GlossaryTemplate;
  onSelect: (t: GlossaryTemplate) => void;
  isLoading: boolean;
  termsLabel: string;
}) {
  const icon = TEMPLATE_ICONS[template.id] ?? <BookOpen className="size-5" />;
  const colorClass = TEMPLATE_COLORS[template.id] ?? 'bg-muted text-foreground border-border hover:bg-muted/80';

  return (
    <button
      type="button"
      onClick={() => onSelect(template)}
      disabled={isLoading}
      className={cn(
        'flex flex-col gap-2 rounded-lg border p-3 text-start transition-colors disabled:opacity-50 disabled:cursor-not-allowed',
        colorClass
      )}
    >
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          {icon}
          <span className="text-sm font-medium leading-tight">
            {template.name.split(' - ')[0]}
          </span>
        </div>
        <Badge variant="secondary" className="shrink-0 text-xs font-normal">
          {template.terms_count} {termsLabel}
        </Badge>
      </div>
      <p className="text-xs opacity-75 line-clamp-2">{template.description}</p>
    </button>
  );
}

function FileUploadZone({
  onTermsParsed,
  disabled,
}: {
  onTermsParsed: (terms: GlossaryTermInput[], filename: string) => void;
  disabled: boolean;
}) {
  const { t } = useI18n();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [status, setStatus] = useState<FileStatus>('idle');
  const [errorMsg, setErrorMsg] = useState('');
  const [parsedFile, setParsedFile] = useState<{ name: string; count: number } | null>(null);

  const processFile = useCallback(async (file: File) => {
    const ext = file.name.split('.').pop()?.toLowerCase();
    const allowed = ['csv', 'xlsx', 'xls', 'ods', 'txt', 'tsv'];
    if (!ext || !allowed.includes(ext)) {
      setStatus('error');
      setErrorMsg(t('glossaries.dialog.errorFormat'));
      return;
    }
    if (file.size > MAX_FILE_SIZE_MB * 1024 * 1024) {
      setStatus('error');
      setErrorMsg(t('glossaries.dialog.errorSize', { max: String(MAX_FILE_SIZE_MB) }));
      return;
    }
    setStatus('parsing');
    setErrorMsg('');
    try {
      const terms = await parseFileToTerms(file);
      if (terms.length === 0) {
        setStatus('error');
        setErrorMsg(t('glossaries.dialog.errorEmpty'));
        return;
      }
      setStatus('success');
      setParsedFile({ name: file.name, count: terms.length });
      onTermsParsed(terms, file.name);
    } catch {
      setStatus('error');
      setErrorMsg(t('glossaries.dialog.errorRead'));
    }
  }, [onTermsParsed, t]);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const file = e.dataTransfer.files[0];
    if (file) processFile(file);
  }, [processFile]);

  const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) processFile(file);
    e.target.value = '';
  }, [processFile]);

  const reset = () => {
    setStatus('idle');
    setParsedFile(null);
    setErrorMsg('');
  };

  return (
    <div className="space-y-3">
      <div
        onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
        onDragLeave={() => setIsDragging(false)}
        onDrop={handleDrop}
        onClick={() => !disabled && fileInputRef.current?.click()}
        className={cn(
          'relative flex flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed p-8 text-center transition-colors cursor-pointer',
          isDragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25 hover:border-primary/50 hover:bg-muted/30',
          disabled && 'opacity-50 cursor-not-allowed',
          status === 'success' && 'border-green-400 bg-green-50',
          status === 'error' && 'border-destructive/50 bg-destructive/5'
        )}
      >
        <input
          ref={fileInputRef}
          type="file"
          accept=".csv,.xlsx,.xls,.ods,.txt,.tsv"
          className="hidden"
          onChange={handleFileChange}
          disabled={disabled}
        />

        {status === 'parsing' && (
          <>
            <Loader2 className="size-8 animate-spin text-primary" />
            <p className="text-sm text-muted-foreground">{t('glossaries.dialog.parsing')}</p>
          </>
        )}

        {status === 'success' && parsedFile && (
          <>
            <CheckCircle2 className="size-8 text-green-600" />
            <div>
              <p className="text-sm font-medium text-green-700">
                {t('glossaries.dialog.termsImported', { count: String(parsedFile.count) })}
              </p>
              <p className="text-xs text-muted-foreground mt-0.5">{parsedFile.name}</p>
            </div>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={(e) => { e.stopPropagation(); reset(); }}
              className="gap-1.5 text-xs"
            >
              <X className="size-3.5" /> {t('glossaries.dialog.changeFile')}
            </Button>
          </>
        )}

        {status === 'error' && (
          <>
            <AlertCircle className="size-8 text-destructive" />
            <div>
              <p className="text-sm font-medium text-destructive">{errorMsg}</p>
            </div>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={(e) => { e.stopPropagation(); reset(); }}
              className="gap-1.5 text-xs"
            >
              <X className="size-3.5" /> {t('glossaries.dialog.retry')}
            </Button>
          </>
        )}

        {status === 'idle' && (
          <>
            <div className="flex size-12 items-center justify-center rounded-full bg-muted">
              <Upload className="size-6 text-muted-foreground" />
            </div>
            <div>
              <p className="text-sm font-medium">{t('glossaries.dialog.dropTitle')}</p>
              <p className="text-xs text-muted-foreground mt-1">{t('glossaries.dialog.dropOr')}</p>
            </div>
            <p className="text-xs text-muted-foreground">{t('glossaries.dialog.dropFormats')}</p>
          </>
        )}
      </div>

      <div className="rounded-md bg-muted/50 p-3 text-xs text-muted-foreground space-y-1">
        <p className="font-medium">{t('glossaries.dialog.formatTitle')}</p>
        <p>{t('glossaries.dialog.formatDesc')}</p>
        <div className="font-mono bg-background rounded border px-2 py-1 mt-1">
          <div className="text-muted-foreground">source,target</div>
          <div>server,server</div>
          <div>database,database</div>
        </div>
        <p className="mt-1">{t('glossaries.dialog.formatNote')}</p>
      </div>
    </div>
  );
}

export function CreateGlossaryDialog({
  open,
  onOpenChange,
  onCreate,
  onImportTemplate,
  isCreating,
  isImportingTemplate,
}: CreateGlossaryDialogProps) {
  const { t } = useI18n();
  const [activeTab, setActiveTab] = useState<'templates' | 'file' | 'manual'>('templates');
  const [name, setName] = useState('');
  const [nameAutoFilled, setNameAutoFilled] = useState(false);
  const [terms, setTerms] = useState<GlossaryTermInput[]>([{ source: '', target: '' }]);
  const [fileTerms, setFileTerms] = useState<GlossaryTermInput[]>([]);
  const [selectedTemplate, setSelectedTemplate] = useState<GlossaryTemplate | null>(null);

  const { templates, isLoading: isLoadingTemplates } = useGlossaryTemplates();

  const isProcessing = isCreating || isImportingTemplate;

  const reset = useCallback(() => {
    setName('');
    setNameAutoFilled(false);
    setTerms([{ source: '', target: '' }]);
    setFileTerms([]);
    setSelectedTemplate(null);
    setActiveTab('templates');
  }, []);

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

  const handleTemplateSelect = useCallback((template: GlossaryTemplate) => {
    setSelectedTemplate(template);
    if (!name || nameAutoFilled) {
      setName(template.name.split(' - ')[0]);
      setNameAutoFilled(true);
    }
  }, [name, nameAutoFilled]);

  const handleFileTermsParsed = useCallback((parsed: GlossaryTermInput[], filename: string) => {
    setFileTerms(parsed);
    if (!name || nameAutoFilled) {
      const baseName = filename.replace(/\.[^.]+$/, '').replace(/[_-]/g, ' ');
      setName(baseName);
      setNameAutoFilled(true);
    }
  }, [name, nameAutoFilled]);

  const handleSubmit = useCallback(async () => {
    if (!name.trim()) return;

    if (activeTab === 'templates' && selectedTemplate) {
      await onImportTemplate(selectedTemplate.id, name.trim());
      reset();
      return;
    }

    const termsToSave = activeTab === 'file'
      ? fileTerms
      : terms.filter(t => t.source.trim() && t.target.trim());
    await onCreate({ name: name.trim(), terms: termsToSave });
    reset();
  }, [activeTab, selectedTemplate, name, fileTerms, terms, onCreate, onImportTemplate, reset]);

  const canSubmit = (() => {
    if (!name.trim() || isProcessing) return false;
    if (activeTab === 'templates') return !!selectedTemplate;
    if (activeTab === 'file') return fileTerms.length > 0;
    return terms.some(t => t.source.trim() && t.target.trim());
  })();

  const submitLabel = (() => {
    if (isProcessing) {
      return activeTab === 'templates'
        ? t('glossaries.dialog.importing')
        : t('glossaries.dialog.creating');
    }
    if (activeTab === 'templates') {
      return selectedTemplate
        ? t('glossaries.dialog.importBtn', { count: String(selectedTemplate.terms_count) })
        : t('glossaries.dialog.selectPrompt');
    }
    if (activeTab === 'file') {
      return fileTerms.length > 0
        ? t('glossaries.dialog.importBtn', { count: String(fileTerms.length) })
        : t('glossaries.dialog.dropTitle');
    }
    const count = terms.filter(t => t.source.trim() && t.target.trim()).length;
    return count > 0
      ? t('glossaries.dialog.createBtn', { count: String(count) })
      : t('glossaries.dialog.createEmpty');
  })();

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-2xl max-h-[90vh] flex flex-col overflow-hidden">
        <DialogHeader className="shrink-0">
          <DialogTitle>{t('glossaries.dialog.title')}</DialogTitle>
          <DialogDescription>{t('glossaries.dialog.description')}</DialogDescription>
        </DialogHeader>

        <div className="shrink-0 space-y-2 pt-2">
          <Label htmlFor="glossary-name">{t('glossaries.dialog.nameLabel')}</Label>
          <Input
            id="glossary-name"
            value={name}
            onChange={(e) => { setName(e.target.value); setNameAutoFilled(false); }}
            placeholder={t('glossaries.dialog.namePlaceholder')}
            disabled={isProcessing}
          />
        </div>

        <Tabs
          value={activeTab}
          onValueChange={(v) => setActiveTab(v as typeof activeTab)}
          className="flex flex-col flex-1 min-h-0 mt-4"
        >
          <TabsList className="shrink-0 w-full grid grid-cols-3">
            <TabsTrigger value="templates" className="gap-1.5 text-xs">
              <BookOpen className="size-3.5" />
              {t('glossaries.dialog.tabTemplates')}
            </TabsTrigger>
            <TabsTrigger value="file" className="gap-1.5 text-xs">
              <FileText className="size-3.5" />
              {t('glossaries.dialog.tabFile')}
            </TabsTrigger>
            <TabsTrigger value="manual" className="gap-1.5 text-xs">
              <PenLine className="size-3.5" />
              {t('glossaries.dialog.tabManual')}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="templates" className="flex-1 overflow-y-auto mt-4 space-y-3">
            {isLoadingTemplates ? (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="size-6 animate-spin text-muted-foreground" />
              </div>
            ) : (
              <>
                <p className="text-xs text-muted-foreground">
                  {t('glossaries.dialog.templatesDesc')}
                </p>
                <div className="grid gap-2 sm:grid-cols-2">
                  {templates.map((template) => (
                    <div
                      key={template.id}
                      className={cn(
                        'relative',
                        selectedTemplate?.id === template.id && 'ring-2 ring-primary ring-offset-1 rounded-lg'
                      )}
                    >
                      {selectedTemplate?.id === template.id && (
                        <CheckCircle2 className="absolute -top-1.5 -right-1.5 size-4 text-primary bg-background rounded-full z-10" />
                      )}
                      <TemplateCard
                        template={template}
                        onSelect={handleTemplateSelect}
                        isLoading={isProcessing}
                        termsLabel={t('glossaries.dialog.terms')}
                      />
                    </div>
                  ))}
                </div>
                {templates.length === 0 && !isLoadingTemplates && (
                  <p className="text-sm text-muted-foreground text-center py-8">
                    {t('glossaries.dialog.templatesEmpty')}
                  </p>
                )}
              </>
            )}
          </TabsContent>

          <TabsContent value="file" className="flex-1 overflow-y-auto mt-4">
            <FileUploadZone
              onTermsParsed={handleFileTermsParsed}
              disabled={isProcessing}
            />
          </TabsContent>

          <TabsContent value="manual" className="flex-1 overflow-y-auto mt-4">
            <TermEditor
              terms={terms}
              onChange={setTerms}
              disabled={isProcessing}
            />
          </TabsContent>
        </Tabs>

        <DialogFooter className="shrink-0 pt-4 border-t mt-2">
          <Button
            variant="outline"
            onClick={() => handleOpenChange(false)}
            disabled={isProcessing}
          >
            {t('glossaries.dialog.cancel')}
          </Button>
          <Button onClick={handleSubmit} disabled={!canSubmit}>
            {isProcessing && <Loader2 className="size-3.5 animate-spin me-1.5" />}
            {submitLabel}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
