"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import { AUDIT_QUESTIONNAIRE } from "@/lib/audits/scoring";
import type {
  AuditKpiSnapshot,
  AuditSimulationView,
  InstitutionalDossierFreshness,
  InstitutionalDossierLoadStrategy,
  InstitutionalDossierPayload,
} from "@/lib/audits/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog } from "@/components/ui/dialog";
import { Tabs } from "@/components/ui/tabs";

type PreventiveDossierViewProps = {
  initialSimulations: AuditSimulationView[];
  initialKpis: AuditKpiSnapshot;
  initialDossier: InstitutionalDossierPayload | null;
  initialFreshness: InstitutionalDossierFreshness | null;
};

type ApiPayload = {
  ok?: boolean;
  error?: string;
  simulations?: AuditSimulationView[];
  simulation?: AuditSimulationView;
  kpis?: AuditKpiSnapshot;
  dossier?: InstitutionalDossierPayload;
  freshness?: InstitutionalDossierFreshness;
};

type AuditAiFindings = {
  auditorLikelyFindings: {
    area: string;
    finding: string;
    severity: "alto" | "medio" | "bajo";
  }[];
  missingEvidence: string[];
  topRisks: string[];
  remediationPlan: {
    step: string;
    priority: "alta" | "media" | "baja";
    ownerSuggestion: string;
    targetDate: string;
  }[];
  confidence: "low" | "medium" | "high";
};

function formatDate(value: string | null) {
  if (!value) {
    return "Sin fecha";
  }

  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return "Sin fecha";
  }

  return parsed.toLocaleString("es-MX", {
    year: "numeric",
    month: "short",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function formatFileSize(bytes: number) {
  if (!Number.isFinite(bytes) || bytes <= 0) {
    return "N/D";
  }

  if (bytes < 1024) {
    return `${bytes} B`;
  }

  if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  }

  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export function PreventiveDossierView({ initialSimulations, initialKpis, initialDossier, initialFreshness }: PreventiveDossierViewProps) {
  const [simulations, setSimulations] = useState(initialSimulations);
  const [kpis, setKpis] = useState(initialKpis);
  const [dossier, setDossier] = useState(initialDossier);
  const [freshness, setFreshness] = useState<InstitutionalDossierFreshness | null>(initialFreshness);
  const [selectedSimulationId, setSelectedSimulationId] = useState(initialSimulations[0]?.id ?? "");

  const [newSimulation, setNewSimulation] = useState({
    name: "",
    auditType: "Preventiva integral",
  });

  const [answers, setAnswers] = useState<Record<string, string>>(() =>
    Object.fromEntries(AUDIT_QUESTIONNAIRE.map((question) => [question.key, "si"])),
  );

  const [isBusy, setIsBusy] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isLoadingAiFindings, setIsLoadingAiFindings] = useState(false);
  const [aiFindings, setAiFindings] = useState<AuditAiFindings | null>(null);
  const [aiSuggestionId, setAiSuggestionId] = useState<string | null>(null);

  const continuityWarnings = useMemo(() => {
    if (!dossier) {
      return [];
    }

    const missingComponents = dossier.components
      .filter((component) => component.totalItems > 0 && component.withEvidence < component.totalItems)
      .map((component) => `Continuidad incompleta en ${component.label}: ${component.withEvidence}/${component.totalItems} con evidencia.`);

    return missingComponents;
  }, [dossier]);

  const selectedSimulation = useMemo(
    () => simulations.find((item) => item.id === selectedSimulationId) ?? null,
    [simulations, selectedSimulationId],
  );

  async function reloadSimulations() {
    const response = await fetch("/api/audits/simulations");
    const payload = (await response.json().catch(() => ({}))) as ApiPayload;

    if (!response.ok || !payload.ok || !payload.simulations || !payload.kpis) {
      throw new Error(payload.error ?? "No fue posible recargar simulaciones.");
    }

    setSimulations(payload.simulations);
    setKpis(payload.kpis);

    if (!selectedSimulationId && payload.simulations[0]?.id) {
      setSelectedSimulationId(payload.simulations[0].id);
    }
  }

  async function createSimulation() {
    setIsBusy(true);
    setErrorMessage(null);

    try {
      const response = await fetch("/api/audits/simulations", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(newSimulation),
      });

      const payload = (await response.json().catch(() => ({}))) as ApiPayload;

      if (!response.ok || !payload.ok || !payload.simulation) {
        setErrorMessage(payload.error ?? "No fue posible crear la simulacion.");
        return;
      }

      setNewSimulation({
        name: "",
        auditType: "Preventiva integral",
      });
      setSelectedSimulationId(payload.simulation.id);
      setMessage("Simulacion creada.");
      await reloadSimulations();
    } catch {
      setErrorMessage("No fue posible crear la simulacion.");
    } finally {
      setIsBusy(false);
    }
  }

  async function scoreSimulation() {
    if (!selectedSimulationId) {
      setErrorMessage("Selecciona una simulacion para calificar.");
      return;
    }

    setIsBusy(true);
    setErrorMessage(null);

    try {
      const response = await fetch(`/api/audits/simulations/${encodeURIComponent(selectedSimulationId)}/score`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          responses: AUDIT_QUESTIONNAIRE.map((question) => ({
            questionKey: question.key,
            answer: answers[question.key] ?? "si",
            evidenceRefs: [],
          })),
        }),
      });

      const payload = (await response.json().catch(() => ({}))) as ApiPayload;

      if (!response.ok || !payload.ok || !payload.simulation) {
        setErrorMessage(payload.error ?? "No fue posible calcular la simulacion.");
        return;
      }

      setMessage("Simulacion calificada.");
      await reloadSimulations();
    } catch {
      setErrorMessage("No fue posible calcular la simulacion.");
    } finally {
      setIsBusy(false);
    }
  }

  async function loadDossier(strategy: InstitutionalDossierLoadStrategy) {
    setIsBusy(true);
    setErrorMessage(null);

    try {
      const response = await fetch(`/api/audits/expediente?strategy=${encodeURIComponent(strategy)}`);
      const payload = (await response.json().catch(() => ({}))) as ApiPayload;

      if (!response.ok || !payload.ok || !payload.dossier || !payload.freshness) {
        setErrorMessage(payload.error ?? "No fue posible cargar el expediente.");
        return;
      }

      setDossier(payload.dossier);
      setFreshness(payload.freshness);
      setMessage(
        payload.freshness.source === "snapshot"
          ? "Expediente cargado desde snapshot."
          : "Expediente cargado en modo vivo.",
      );
    } catch {
      setErrorMessage("No fue posible cargar el expediente.");
    } finally {
      setIsBusy(false);
    }
  }

  async function refreshDossier() {
    setIsBusy(true);
    setErrorMessage(null);

    try {
      const response = await fetch("/api/audits/expediente/refresh", {
        method: "POST",
      });
      const payload = (await response.json().catch(() => ({}))) as ApiPayload;

      if (!response.ok || !payload.ok || !payload.dossier) {
        setErrorMessage(payload.error ?? "No fue posible refrescar el expediente.");
        return;
      }

      setDossier(payload.dossier);
      setFreshness(payload.freshness ?? null);
      setMessage("Snapshot del expediente institucional actualizado.");
      await reloadSimulations();
    } catch {
      setErrorMessage("No fue posible refrescar el expediente.");
    } finally {
      setIsBusy(false);
    }
  }

  async function setSuggestionDecision(decision: "accept" | "dismiss") {
    if (!aiSuggestionId) {
      return;
    }

    await fetch(`/api/ai/suggestions/${encodeURIComponent(aiSuggestionId)}/decision`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ decision }),
    });
  }

  async function generateAiFindings() {
    setIsLoadingAiFindings(true);
    setErrorMessage(null);

    try {
      const response = await fetch("/api/audits/ai/findings", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          simulationId: selectedSimulationId || undefined,
        }),
      });

      const payload = (await response.json().catch(() => ({}))) as {
        ok?: boolean;
        error?: string;
        auditorLikelyFindings?: AuditAiFindings["auditorLikelyFindings"];
        missingEvidence?: AuditAiFindings["missingEvidence"];
        topRisks?: AuditAiFindings["topRisks"];
        remediationPlan?: AuditAiFindings["remediationPlan"];
        confidence?: AuditAiFindings["confidence"];
        suggestionId?: string;
      };

      if (!response.ok || !payload.ok) {
        setErrorMessage(payload.error ?? "No fue posible generar dictamen IA.");
        return;
      }

      setAiFindings({
        auditorLikelyFindings: payload.auditorLikelyFindings ?? [],
        missingEvidence: payload.missingEvidence ?? [],
        topRisks: payload.topRisks ?? [],
        remediationPlan: payload.remediationPlan ?? [],
        confidence: payload.confidence ?? "low",
      });
      setAiSuggestionId(payload.suggestionId ?? null);
      setMessage("Dictamen IA generado.");
    } catch {
      setErrorMessage("No fue posible generar dictamen IA.");
    } finally {
      setIsLoadingAiFindings(false);
    }
  }

  return (
    <div className="space-y-4">
      <section className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Auditorias completadas</p>
            <p className="mt-2 text-4xl font-semibold text-[#15294d]">{kpis.completedAudits}</p>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Ultima calificacion</p>
            <p className="mt-2 text-4xl font-semibold text-[#15294d]">{kpis.lastScore ?? 0}</p>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Contratos registrados</p>
            <p className="mt-2 text-4xl font-semibold text-[#15294d]">{kpis.registeredContracts}</p>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">PDFs resguardados</p>
            <p className="mt-2 text-4xl font-semibold text-[#15294d]">{kpis.securedPdfs}</p>
          </CardContent>
        </Card>
      </section>

      {errorMessage ? <p className="rounded-xl border border-[#efc4c4] bg-[#fff1f1] px-3 py-2 text-sm text-[#ad3f3f]">{errorMessage}</p> : null}
      {message ? <p className="rounded-xl border border-[#bde5ce] bg-[#ecf9f1] px-3 py-2 text-sm text-[#1f7f4f]">{message}</p> : null}

      <Tabs
        defaultTab="simulator"
        items={[
          {
            id: "simulator",
            label: "Simulador",
            content: (
              <div className="space-y-3">
                <Dialog triggerLabel="Nueva Simulacion" title="Nueva Simulacion" description="Configura simulacion de auditoria preventiva">
                  <div className="space-y-2">
                    <input
                      value={newSimulation.name}
                      onChange={(event) => setNewSimulation((prev) => ({ ...prev, name: event.target.value }))}
                      placeholder="Nombre"
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3"
                    />
                    <input
                      value={newSimulation.auditType}
                      onChange={(event) => setNewSimulation((prev) => ({ ...prev, auditType: event.target.value }))}
                      placeholder="Tipo de auditoria"
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3"
                    />
                    <Button onClick={createSimulation} disabled={isBusy}>
                      Guardar simulacion
                    </Button>
                  </div>
                </Dialog>

                <select
                  value={selectedSimulationId}
                  onChange={(event) => setSelectedSimulationId(event.target.value)}
                  className="h-10 w-full rounded-lg border border-[#cfd8e7] bg-white px-3 text-sm"
                >
                  <option value="">Selecciona simulacion</option>
                  {simulations.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.name} ({item.status})
                    </option>
                  ))}
                </select>

                <Card>
                  <CardContent className="space-y-2 py-5">
                    <p className="text-sm font-semibold text-[#1d335a]">Cuestionario de scoring</p>
                    {AUDIT_QUESTIONNAIRE.map((question) => (
                      <label key={question.key} className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-[#dbe3f1] px-3 py-2 text-sm">
                        <span className="text-[#2e466e]">{question.prompt}</span>
                        <select
                          value={answers[question.key] ?? "si"}
                          onChange={(event) =>
                            setAnswers((prev) => ({
                              ...prev,
                              [question.key]: event.target.value,
                            }))
                          }
                          className="h-8 rounded-lg border border-[#cfd8e7] bg-white px-2 text-xs"
                        >
                          <option value="si">Si</option>
                          <option value="parcial">Parcial</option>
                          <option value="no">No</option>
                        </select>
                      </label>
                    ))}

                    <Button onClick={scoreSimulation} disabled={isBusy || !selectedSimulationId}>
                      Calificar simulacion
                    </Button>
                  </CardContent>
                </Card>

                {selectedSimulation ? (
                  <Card>
                    <CardContent className="space-y-2 py-5">
                      <p className="text-sm font-semibold text-[#1d335a]">Resultado actual</p>
                      <p className="text-sm text-[#60718f]">Status: {selectedSimulation.status}</p>
                      <p className="text-sm text-[#60718f]">Score: {selectedSimulation.overallScore ?? 0}</p>
                      <p className="text-sm text-[#60718f]">Completada: {formatDate(selectedSimulation.completedAt)}</p>
                      {selectedSimulation.sections.map((section) => (
                        <article key={section.id} className="rounded-lg border border-[#dbe3f1] bg-white p-2 text-xs text-[#506180]">
                          <p className="font-semibold">{section.key}</p>
                          <p>Status: {section.status}</p>
                          <p>Score: {section.score ?? 0}</p>
                        </article>
                      ))}
                    </CardContent>
                  </Card>
                ) : null}
              </div>
            ),
          },
          {
            id: "dossier",
            label: "Expediente",
            content: (
              <div className="space-y-3">
                <div className="flex flex-wrap gap-2">
                  <Button variant="secondary" onClick={() => void loadDossier("live")} disabled={isBusy}>
                    Cargar modo vivo (default)
                  </Button>
                  <Button variant="secondary" onClick={() => void loadDossier("snapshot")} disabled={isBusy}>
                    Cargar ultimo snapshot
                  </Button>
                  <Button onClick={refreshDossier} disabled={isBusy}>
                    Generar nuevo snapshot
                  </Button>
                </div>

                {freshness ? (
                  <Card>
                    <CardContent className="space-y-2 py-5 text-sm text-[#385073]">
                      <p>
                        Estrategia solicitada: <strong>{freshness.strategy}</strong> | Fuente actual: <strong>{freshness.source}</strong>
                      </p>
                      <p>Generado: {formatDate(freshness.generatedAt)}</p>
                      <p>
                        Estado de frescura:{" "}
                        <span className={freshness.isStale ? "font-semibold text-[#ad3f3f]" : "font-semibold text-[#1f7f4f]"}>
                          {freshness.isStale ? "Desactualizado" : "Vigente"}
                        </span>{" "}
                        (umbral: {freshness.staleAfterMinutes} min)
                      </p>
                      {freshness.snapshotId ? <p>Snapshot ID: {freshness.snapshotId}</p> : null}
                    </CardContent>
                  </Card>
                ) : null}
                {continuityWarnings.length > 0 ? (
                  <Card>
                    <CardContent className="space-y-2 py-5">
                      <p className="text-sm font-semibold text-[#8d6308]">Advertencias de continuidad</p>
                      {continuityWarnings.map((warning) => (
                        <p key={warning} className="rounded-lg border border-[#f0deb0] bg-[#fff8e9] px-2 py-1 text-xs text-[#8d6308]">
                          {warning}
                        </p>
                      ))}
                    </CardContent>
                  </Card>
                ) : null}

                {!dossier ? <p className="text-sm text-[#60718f]">Sin expediente generado todavia.</p> : null}

                {dossier ? (
                  <>
                    <Card>
                      <CardContent className="grid gap-2 py-5 text-sm text-[#385073] md:grid-cols-3 xl:grid-cols-4">
                        <p>Contratos: {dossier.summary.contracts}</p>
                        <p>PDF contratos: {dossier.summary.contractDocuments}</p>
                        <p>Propuestas: {dossier.summary.proposals}</p>
                        <p>PDF propuestas: {dossier.summary.proposalDocuments}</p>
                        <p>Casos legales: {dossier.summary.legalCases}</p>
                        <p>Escritos legales: {dossier.summary.legalDocuments}</p>
                        <p>Alertas alto riesgo: {dossier.summary.highRiskAlerts}</p>
                      </CardContent>
                    </Card>

                    <div className="grid gap-3 md:grid-cols-2">
                      {dossier.components.map((component) => (
                        <article key={component.key} className="rounded-xl border border-[#d8e1ef] bg-white p-3 text-sm">
                          <p className="font-semibold text-[#1d335a]">{component.label}</p>
                          <p className="mt-1 text-[#60718f]">Estado: {component.status}</p>
                          <p className="mt-1 text-[#60718f]">
                            Evidencia: {component.withEvidence}/{component.totalItems}
                          </p>
                        </article>
                      ))}
                    </div>

                    <Card>
                      <CardContent className="space-y-2 py-5">
                        <p className="text-sm font-semibold text-[#1d335a]">Propuestas en expediente (M5)</p>
                        {dossier.proposals.length === 0 ? <p className="text-sm text-[#60718f]">Sin propuestas.</p> : null}
                        {dossier.proposals.map((item) => (
                          <article key={item.id} className="rounded-lg border border-[#dbe3f1] bg-white p-2 text-xs text-[#506180]">
                            <p className="font-semibold">{item.title}</p>
                            <p>
                              {item.status} | Documentos {item.documents}
                            </p>
                            <div className="mt-1 flex flex-wrap gap-2">
                              {item.links.map((link) => (
                                <Link key={`${item.id}-${link.href}`} href={link.href} className="text-[#2b5fab] underline">
                                  {link.label}
                                </Link>
                              ))}
                            </div>
                            {item.documentEntries.length > 0 ? (
                              <details className="mt-2 rounded-md border border-[#e4ebf6] p-2">
                                <summary className="cursor-pointer font-semibold">Ver documentos y trazabilidad ({item.documentEntries.length})</summary>
                                <div className="mt-2 space-y-2">
                                  {item.documentEntries.map((document) => (
                                    <article key={document.id} className="rounded-md border border-[#edf2fa] bg-[#f9fbff] p-2">
                                      <p className="font-semibold">{document.fileName}</p>
                                      <p className="mt-1 inline-flex rounded-full border border-[#c9d9f0] bg-white px-2 py-0.5 text-[11px] font-semibold text-[#315b96]">
                                        Por que este archivo
                                      </p>
                                      <p>
                                        {document.mimeType} | {formatFileSize(document.sizeBytes)} | {formatDate(document.createdAt)}
                                      </p>
                                      <p className="mt-1">{document.traceLabel}</p>
                                      <div className="mt-1 flex flex-wrap gap-2">
                                        {document.links.map((link) => (
                                          <Link key={`${document.id}-${link.href}`} href={link.href} className="text-[#2b5fab] underline">
                                            {link.label}
                                          </Link>
                                        ))}
                                      </div>
                                    </article>
                                  ))}
                                </div>
                              </details>
                            ) : null}
                          </article>
                        ))}
                      </CardContent>
                    </Card>

                    <Card>
                      <CardContent className="space-y-2 py-5">
                        <p className="text-sm font-semibold text-[#1d335a]">Contratos en expediente (M8)</p>
                        {dossier.contracts.length === 0 ? <p className="text-sm text-[#60718f]">Sin contratos.</p> : null}
                        {dossier.contracts.map((item) => (
                          <article key={item.id} className="rounded-lg border border-[#dbe3f1] bg-white p-2 text-xs text-[#506180]">
                            <p className="font-semibold">{item.title}</p>
                            <p>
                              {item.status} | Entregables {item.deliverables} | Pagos {item.payments} | Documentos {item.documents}
                            </p>
                            <div className="mt-1 flex flex-wrap gap-2">
                              {item.links.map((link) => (
                                <Link key={`${item.id}-${link.href}`} href={link.href} className="text-[#2b5fab] underline">
                                  {link.label}
                                </Link>
                              ))}
                            </div>
                            {item.documentEntries.length > 0 ? (
                              <details className="mt-2 rounded-md border border-[#e4ebf6] p-2">
                                <summary className="cursor-pointer font-semibold">Ver documentos y trazabilidad ({item.documentEntries.length})</summary>
                                <div className="mt-2 space-y-2">
                                  {item.documentEntries.map((document) => (
                                    <article key={document.id} className="rounded-md border border-[#edf2fa] bg-[#f9fbff] p-2">
                                      <p className="font-semibold">{document.fileName}</p>
                                      <p className="mt-1 inline-flex rounded-full border border-[#c9d9f0] bg-white px-2 py-0.5 text-[11px] font-semibold text-[#315b96]">
                                        Por que este archivo
                                      </p>
                                      <p>
                                        {document.kind ? `${document.kind} | ` : ""}
                                        {document.mimeType} | {formatFileSize(document.sizeBytes)} | {formatDate(document.createdAt)}
                                      </p>
                                      <p className="mt-1">{document.traceLabel}</p>
                                      <div className="mt-1 flex flex-wrap gap-2">
                                        {document.links.map((link) => (
                                          <Link key={`${document.id}-${link.href}`} href={link.href} className="text-[#2b5fab] underline">
                                            {link.label}
                                          </Link>
                                        ))}
                                      </div>
                                    </article>
                                  ))}
                                </div>
                              </details>
                            ) : null}
                          </article>
                        ))}
                      </CardContent>
                    </Card>

                    <Card>
                      <CardContent className="space-y-2 py-5">
                        <p className="text-sm font-semibold text-[#1d335a]">Casos legales en expediente (M9)</p>
                        {dossier.legal.length === 0 ? <p className="text-sm text-[#60718f]">Sin casos legales.</p> : null}
                        {dossier.legal.map((item) => (
                          <article key={item.id} className="rounded-lg border border-[#dbe3f1] bg-white p-2 text-xs text-[#506180]">
                            <p className="font-semibold">
                              {item.caseType} | {item.severity}
                            </p>
                            <p>
                              {item.status} | Escritos {item.documents}
                            </p>
                            <div className="mt-1 flex flex-wrap gap-2">
                              {item.links.map((link) => (
                                <Link key={`${item.id}-${link.href}`} href={link.href} className="text-[#2b5fab] underline">
                                  {link.label}
                                </Link>
                              ))}
                            </div>
                            {item.documentEntries.length > 0 ? (
                              <details className="mt-2 rounded-md border border-[#e4ebf6] p-2">
                                <summary className="cursor-pointer font-semibold">Ver documentos y trazabilidad ({item.documentEntries.length})</summary>
                                <div className="mt-2 space-y-2">
                                  {item.documentEntries.map((document) => (
                                    <article key={document.id} className="rounded-md border border-[#edf2fa] bg-[#f9fbff] p-2">
                                      <p className="font-semibold">{document.fileName}</p>
                                      <p className="mt-1 inline-flex rounded-full border border-[#c9d9f0] bg-white px-2 py-0.5 text-[11px] font-semibold text-[#315b96]">
                                        Por que este archivo
                                      </p>
                                      <p>
                                        {document.kind ? `${document.kind} | ` : ""}
                                        {document.mimeType} | {formatFileSize(document.sizeBytes)} | {formatDate(document.createdAt)}
                                      </p>
                                      <p className="mt-1">{document.traceLabel}</p>
                                      <div className="mt-1 flex flex-wrap gap-2">
                                        {document.links.map((link) => (
                                          <Link key={`${document.id}-${link.href}`} href={link.href} className="text-[#2b5fab] underline">
                                            {link.label}
                                          </Link>
                                        ))}
                                      </div>
                                    </article>
                                  ))}
                                </div>
                              </details>
                            ) : null}
                          </article>
                        ))}
                      </CardContent>
                    </Card>
                  </>
                ) : null}
              </div>
            ),
          },
          {
            id: "dictamen-ia",
            label: "Dictamen IA",
            content: (
              <div className="space-y-3">
                <div className="flex flex-wrap gap-2">
                  <Button type="button" variant="secondary" disabled={isLoadingAiFindings} onClick={() => void generateAiFindings()}>
                    {isLoadingAiFindings ? "Generando dictamen IA..." : "Generar dictamen IA"}
                  </Button>
                  {aiFindings ? (
                    <Button
                      type="button"
                      variant="secondary"
                      onClick={() => {
                        void setSuggestionDecision("dismiss");
                        setAiFindings(null);
                        setMessage("Dictamen IA descartado.");
                      }}
                    >
                      Descartar dictamen IA
                    </Button>
                  ) : null}
                </div>

                {!aiFindings ? <p className="text-sm text-[#60718f]">Genera dictamen IA para simular observaciones de auditor.</p> : null}

                {aiFindings ? (
                  <>
                    <article className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                      <p className="text-sm font-semibold text-[#1d335a]">Hallazgos probables del auditor</p>
                      <ul className="mt-2 space-y-2 text-xs text-[#60718f]">
                        {aiFindings.auditorLikelyFindings.map((item) => (
                          <li key={`${item.area}-${item.finding}`} className="rounded-lg border border-[#e4ebf6] px-2 py-1">
                            <p className="font-semibold text-[#233b62]">
                              {item.area} · {item.severity}
                            </p>
                            <p>{item.finding}</p>
                          </li>
                        ))}
                      </ul>
                    </article>

                    <article className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                      <p className="text-sm font-semibold text-[#1d335a]">Evidencia faltante</p>
                      <ul className="mt-2 space-y-1 text-xs text-[#60718f]">
                        {aiFindings.missingEvidence.map((item) => (
                          <li key={item}>- {item}</li>
                        ))}
                      </ul>
                    </article>

                    <article className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                      <p className="text-sm font-semibold text-[#1d335a]">Top riesgos</p>
                      <ul className="mt-2 space-y-1 text-xs text-[#60718f]">
                        {aiFindings.topRisks.map((item) => (
                          <li key={item}>- {item}</li>
                        ))}
                      </ul>
                    </article>

                    <article className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                      <p className="text-sm font-semibold text-[#1d335a]">Plan de remediacion</p>
                      <ul className="mt-2 space-y-2 text-xs text-[#60718f]">
                        {aiFindings.remediationPlan.map((item) => (
                          <li key={`${item.step}-${item.ownerSuggestion}`} className="rounded-lg border border-[#e4ebf6] px-2 py-1">
                            <p className="font-semibold text-[#233b62]">{item.step}</p>
                            <p>
                              Prioridad {item.priority} · Responsable sugerido: {item.ownerSuggestion} · Fecha objetivo: {item.targetDate}
                            </p>
                          </li>
                        ))}
                      </ul>
                      <div className="mt-3 flex flex-wrap items-center gap-2">
                        <Button
                          type="button"
                          size="sm"
                          onClick={() => {
                            void setSuggestionDecision("accept");
                            setMessage("Dictamen IA marcado como aceptado.");
                          }}
                        >
                          Aceptar dictamen IA
                        </Button>
                        <p className="text-xs font-semibold text-[#405578]">Confianza IA: {aiFindings.confidence}</p>
                      </div>
                    </article>
                  </>
                ) : null}
              </div>
            ),
          },
        ]}
      />
    </div>
  );
}
