import { useState } from 'react';
import { ClipboardPaste, CheckCircle, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';

import api, { type ImportResult } from '@/lib/api';
import { formatAmount } from '@/lib/format';
import { formatShortDate } from '@/lib/dates';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';

interface Props {
  onClose: () => void;
  onImported: () => void;
}

export default function PasteImportModal({ onClose, onImported }: Props) {
  const [text, setText] = useState('');
  const [bank, setBank] = useState('BAC');
  const [source, setSource] = useState('CREDIT_CARD');
  const [importing, setImporting] = useState(false);
  const [result, setResult] = useState<ImportResult | null>(null);

  const handleImport = async () => {
    if (!text.trim()) return;
    setImporting(true);
    try {
      const { data } = await api.post<ImportResult>('/import/paste', { text, bank, source });
      setResult(data);
      if (data.imported > 0) onImported();
    } catch {
      toast.error('No se pudo importar - revisa el formato');
    } finally {
      setImporting(false);
    }
  };

  // Re-import ONLY the skipped lines with the dedup check disabled, so rows
  // that imported on the first pass are never duplicated.
  const handleImportDuplicates = async () => {
    if (!result || result.skipped.length === 0) return;
    const lines = text.trim().split('\n');
    const dupText = result.skipped
      .map((s) => lines[s.line - 1])
      .filter(Boolean)
      .join('\n');
    setImporting(true);
    try {
      const { data } = await api.post<ImportResult>('/import/paste', {
        text: dupText,
        bank,
        source,
        allow_duplicates: true,
      });
      toast.success(`${data.imported} duplicado(s) importados`);
      setResult({
        ...result,
        imported: result.imported + data.imported,
        skipped: [],
        duplicates: 0,
      });
      onImported();
    } catch {
      toast.error('No se pudieron importar los duplicados');
    } finally {
      setImporting(false);
    }
  };

  return (
    <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>
      <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <ClipboardPaste className="w-4 h-4 text-primary" />
            Import Bank Statement
          </DialogTitle>
        </DialogHeader>

        {!result ? (
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Bank</Label>
                <Select value={bank} onValueChange={(v) => v && setBank(v)}>
                  <SelectTrigger className="w-full">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="BAC">BAC</SelectItem>
                    <SelectItem value="BCR">BCR</SelectItem>
                    <SelectItem value="DAVIVIENDA">Davivienda</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Source</Label>
                <Select value={source} onValueChange={(v) => v && setSource(v)}>
                  <SelectTrigger className="w-full">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="CREDIT_CARD">Credit Card</SelectItem>
                    <SelectItem value="CASH">Cash</SelectItem>
                    <SelectItem value="TRANSFER">Transfer</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="space-y-2">
              <Label>Statement Text</Label>
              <Textarea
                className="h-48 font-mono text-xs resize-y"
                value={text}
                onChange={(e) => setText(e.target.value)}
                placeholder={`Paste bank statement lines here...\n\nFormat: DD/MM/YYYY\tMERCHANT\\CITY\\COUNTRY\tAMOUNT CRC`}
              />
              <p className="text-xs text-muted-foreground">
                One transaction per line. Tab-separated columns.
              </p>
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={onClose}>
                Cancel
              </Button>
              <Button onClick={handleImport} disabled={importing || !text.trim()}>
                {importing ? 'Importing...' : 'Import'}
              </Button>
            </DialogFooter>
          </div>
        ) : (
          <div className="space-y-4">
            <Alert>
              <CheckCircle className="h-4 w-4 text-primary" />
              <AlertTitle className="text-primary">Import Complete</AlertTitle>
              <AlertDescription>
                {result.imported} imported
                {result.duplicates > 0 && ` · ${result.duplicates} duplicates skipped`}
              </AlertDescription>
            </Alert>

            {result.errors.length > 0 && (
              <Alert variant="destructive">
                <AlertTriangle className="h-4 w-4" />
                <AlertTitle>{result.errors.length} errors</AlertTitle>
                <AlertDescription>
                  <ul className="text-xs font-mono max-h-32 overflow-y-auto space-y-1 mt-1">
                    {result.errors.map((err, i) => (
                      <li key={i}>{err}</li>
                    ))}
                  </ul>
                </AlertDescription>
              </Alert>
            )}

            {result.skipped.length > 0 && (
              <div className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-3 space-y-2">
                <p className="text-sm font-medium">
                  {result.skipped.length} duplicado(s) omitido(s)
                </p>
                <ul className="text-xs max-h-40 overflow-y-auto space-y-1.5">
                  {result.skipped.map((s) => (
                    <li key={`${s.line}-${s.existing_id}`} className="space-y-0.5">
                      <span className="font-mono">
                        {s.merchant} · {formatShortDate(s.date)} ·{' '}
                        {formatAmount(s.amount, s.currency)}
                      </span>
                      <span className="block text-muted-foreground">
                        coincide con #{s.existing_id}: {s.existing_merchant} del{' '}
                        {formatShortDate(s.existing_date)} ({s.existing_source})
                      </span>
                    </li>
                  ))}
                </ul>
                <Button
                  variant="outline"
                  size="sm"
                  className="w-full"
                  onClick={handleImportDuplicates}
                  disabled={importing}
                >
                  {importing
                    ? 'Importando...'
                    : 'Importar duplicados de todos modos'}
                </Button>
              </div>
            )}

            <Button onClick={onClose} className="w-full">
              Done
            </Button>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
