import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogClose,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { FileDown, Copy, X } from 'lucide-react';
import type { AuditScenario, ScenarioResult } from '@/lib/audit/types';
import FallbackDiagram from '@/components/FallbackDiagram';
import { useNavigate } from 'react-router';
import type { RouteModuleMap } from '@/lib/audit/types';

const MODULE_ROUTES: RouteModuleMap = {
  galpao: '/galpao',
  cilindro: '/cilindro',
  vault: '/abobada',
  dome: '/cupula',
  sign: '/muros',
  'isolated-roof': '/cobertura-isolada',
  bar: '/barras',
  bridge: '/pontes',
  tower: '/torres',
  dynamics: '/dinamica',
  'cross-module': '/galpao',
  'edge-case': '/galpao',
  'cpi-variant': '/galpao',
  piperack: '/piperack',
};

interface AuditDetailPopupProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  scenario: AuditScenario | null;
  result: ScenarioResult | null;
}

export default function AuditDetailPopup({ open, onOpenChange, scenario, result }: AuditDetailPopupProps) {
  const navigate = useNavigate();

  if (!scenario) return null;

  const handleCopyToModule = () => {
    const route = MODULE_ROUTES[scenario.module];
    if (route) {
      onOpenChange(false);
      navigate(route);
    }
  };

  const handleExportPDF = () => {
    if (!result) return;
    import('@/lib/audit/export-audit-pdf').then((mod) => {
      const report = {
        id: 'popup-export',
        provider: 'audit',
        model: 'manual',
        timestamp: Date.now(),
        totalScenarios: 1,
        totalPassed: result.verdict === 'PASS' ? 1 : 0,
        totalWarnings: result.verdict === 'WARN' ? 1 : 0,
        totalFailed: result.verdict === 'FAIL' ? 1 : 0,
        modules: [
          {
            module: scenario.module,
            moduleLabel: scenario.moduleLabel,
            totalScenarios: 1,
            passed: result.verdict === 'PASS' ? 1 : 0,
            warnings: result.verdict === 'WARN' ? 1 : 0,
            failed: result.verdict === 'FAIL' ? 1 : 0,
            scenarios: [result],
          },
        ],
        rawResponse: undefined,
      };
      mod.exportAuditReportToPDF(report);
    });
  };

  const statusIcon = (v: string) => {
    switch (v) {
      case 'PASS': return <span className="text-emerald-600 font-bold">✓</span>;
      case 'WARN': return <span className="text-amber-600 font-bold">⚠</span>;
      case 'FAIL': return <span className="text-red-600 font-bold">✗</span>;
      default: return <span className="text-muted-foreground">?</span>;
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-base">
            {scenario.id}
            {result && <span className="text-sm font-normal">{statusIcon(result.verdict)} {result.verdict}</span>}
          </DialogTitle>
          <DialogDescription>
            {scenario.description} — {scenario.moduleLabel} · {scenario.nbrSection}
          </DialogDescription>
        </DialogHeader>

        <div className="w-full h-48 rounded-md overflow-hidden border bg-muted/10 mb-3">
          <FallbackDiagram type={scenario.diagramType as never} props={scenario.diagramProps as never} />
        </div>

        <div className="grid grid-cols-2 gap-2 text-xs mb-3">
          <div className="rounded-md border bg-muted/30 p-2">
            <span className="text-muted-foreground">Módulo:</span>{' '}
            <span className="font-medium">{scenario.moduleLabel}</span>
          </div>
          <div className="rounded-md border bg-muted/30 p-2">
            <span className="text-muted-foreground">NBR:</span>{' '}
            <span className="font-medium">{scenario.nbrSection}</span>
          </div>
        </div>

        {result && result.checks.length > 0 && (
          <div className="space-y-1 mb-3">
            <h4 className="text-sm font-semibold">Verificações</h4>
            <div className="rounded-md border overflow-hidden">
              <table className="w-full text-xs">
                <thead className="bg-muted/50">
                  <tr>
                    <th className="p-2 text-left w-10">Status</th>
                    <th className="p-2 text-left">Check</th>
                    <th className="p-2 text-left">Esperado</th>
                    <th className="p-2 text-left">Obtido</th>
                  </tr>
                </thead>
                <tbody>
                  {result.checks.map((chk, i) => (
                    <tr key={i} className="border-t border-border">
                      <td className="p-2">{statusIcon(chk.status)}</td>
                      <td className="p-2 font-medium">{chk.name}</td>
                      <td className="p-2 text-muted-foreground">{chk.expected}</td>
                      <td className="p-2">{chk.actual}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {result.summary && (
              <p className="text-xs text-muted-foreground mt-1">{result.summary}</p>
            )}
            {result.llmNotes && (
              <p className="text-xs italic text-muted-foreground mt-1">LLM: {result.llmNotes}</p>
            )}
          </div>
        )}

        <div className="space-y-1 mb-3">
          <h4 className="text-sm font-semibold">Entradas</h4>
          <div className="rounded-md border bg-muted/10 p-2 text-xs font-mono max-h-32 overflow-y-auto">
            <pre className="whitespace-pre-wrap">{JSON.stringify(scenario.inputs, null, 2)}</pre>
          </div>
        </div>

        <div className="flex gap-2 justify-end">
          <Button variant="outline" size="sm" onClick={handleExportPDF} disabled={!result}>
            <FileDown className="w-3.5 h-3.5 mr-1.5" />
            Exportar PDF
          </Button>
          <Button variant="outline" size="sm" onClick={handleCopyToModule}>
            <Copy className="w-3.5 h-3.5 mr-1.5" />
            Copiar para o módulo
          </Button>
          <DialogClose asChild>
            <Button variant="ghost" size="sm">
              <X className="w-3.5 h-3.5 mr-1.5" />
              Fechar
            </Button>
          </DialogClose>
        </div>
      </DialogContent>
    </Dialog>
  );
}
