"use client";

import { useEffect, useMemo, useState } from "react";
import type {
  DiagnosisRecommendation,
  LegalCaseView,
  LegalContractOptionView,
  LegalDirectoryEntityView,
  LegalKpiSnapshot,
  LegalTemplateView,
} from "@/lib/legal/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 LegalProtectionViewProps = {
  initialCases: LegalCaseView[];
  initialKpis: LegalKpiSnapshot;
  initialDirectory: LegalDirectoryEntityView[];
  initialTemplates: LegalTemplateView[];
  availableContracts: LegalContractOptionView[];
  prefilledContractId?: string | null;
};

type ApiPayload = {
  ok?: boolean;
  error?: string;
  kpis?: LegalKpiSnapshot;
  cases?: LegalCaseView[];
  case?: LegalCaseView | null;
  diagnosis?: {
    id: string;
    legalCaseId: string | null;
    recommendation: DiagnosisRecommendation;
  };
  escalation?: {
    caseId: string;
    steps: Array<{
      key: string;
      title: string;
      estimatedWindow: string;
      checklist: string[];
      requiresLawyer: boolean;
      dependsOn: string | null;
      completedAt: string | null;
      notes: string;
      isBlocked: boolean;
    }>;
  };
  templates?: LegalTemplateView[];
  entities?: LegalDirectoryEntityView[];
  document?: {
    id: string;
    title: string;
    content: string;
    createdAt: string;
  };
  generation?: {
    warnings?: string[];
  };
};

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 severityTone(severity: LegalCaseView["severity"]) {
  if (severity === "HIGH") {
    return "border-[#f1c7ce] bg-[#fff1f4] text-[#b03f4f]";
  }

  if (severity === "MEDIUM") {
    return "border-[#f0deb0] bg-[#fff8e9] text-[#8d6308]";
  }

  return "border-[#b9e6cd] bg-[#eaf9f1] text-[#1f8b63]";
}

function formatContractOptionLabel(contract: LegalContractOptionView) {
  const numberLabel = contract.contractNumber ? `#${contract.contractNumber}` : "Sin numero";
  return `${contract.title} - ${contract.counterpartyEntity} (${numberLabel})`;
}

export function LegalProtectionView({
  initialCases,
  initialKpis,
  initialDirectory,
  initialTemplates,
  availableContracts,
  prefilledContractId,
}: LegalProtectionViewProps) {
  const [cases, setCases] = useState(initialCases);
  const [kpis, setKpis] = useState(initialKpis);
  const [directory, setDirectory] = useState(initialDirectory);
  const [templates, setTemplates] = useState(initialTemplates);

  const [isBusy, setIsBusy] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const [diagnosisStep, setDiagnosisStep] = useState(1);
  const [diagnosisId, setDiagnosisId] = useState<string | null>(null);
  const [diagnosisRecommendation, setDiagnosisRecommendation] = useState<DiagnosisRecommendation | null>(null);
  const [diagnosisAnswers, setDiagnosisAnswers] = useState({
    breachType: "contract_breach",
    processStage: "none",
    evidenceLevel: "basic",
    urgency: "medium",
    objective: "payment",
    amountAtRisk: "",
    counterparty: "",
    description: "",
  });
  const [diagnosisContractId, setDiagnosisContractId] = useState(prefilledContractId ?? "");

  const [newCase, setNewCase] = useState({
    contractId: prefilledContractId ?? "",
    caseType: "CONTRACT_BREACH",
    severity: "MEDIUM",
    counterparty: "",
    description: "",
    amountAtRisk: "",
    status: "OPEN",
  });

  const [selectedEscalationCaseId, setSelectedEscalationCaseId] = useState("");
  const [escalation, setEscalation] = useState<ApiPayload["escalation"] | null>(null);

  const [documentDraft, setDocumentDraft] = useState({
    legalCaseId: "",
    caseType: "CONTRACT_BREACH",
    severity: "MEDIUM",
    templateKey: "",
    counterparty: "",
    companyName: "",
    amountAtRisk: "",
    description: "",
    objective: "",
    title: "",
  });
  const [generatedDocuments, setGeneratedDocuments] = useState<Array<{ id: string; title: string; content: string; createdAt: string }>>([]);

  const [directoryFilters, setDirectoryFilters] = useState({
    jurisdictionLevel: "",
    q: "",
  });

  const currentEscalationCase = useMemo(
    () => cases.find((item) => item.id === selectedEscalationCaseId) ?? null,
    [cases, selectedEscalationCaseId],
  );
  const contractOptions = useMemo(() => {
    const options = availableContracts.map((item) => ({
      id: item.id,
      label: formatContractOptionLabel(item),
      isPrefilled: item.id === prefilledContractId,
    }));

    if (prefilledContractId && !options.some((item) => item.id === prefilledContractId)) {
      options.unshift({
        id: prefilledContractId,
        label: `${prefilledContractId} (prefill)`,
        isPrefilled: true,
      });
    }

    return options;
  }, [availableContracts, prefilledContractId]);

  async function reloadDataset() {
    const [kpisResponse, casesResponse, templatesResponse] = await Promise.all([
      fetch("/api/legal/kpis"),
      fetch("/api/legal/cases"),
      fetch("/api/legal/templates"),
    ]);

    const kpisPayload = (await kpisResponse.json().catch(() => ({}))) as ApiPayload;
    const casesPayload = (await casesResponse.json().catch(() => ({}))) as ApiPayload;
    const templatesPayload = (await templatesResponse.json().catch(() => ({}))) as ApiPayload;

    if (kpisResponse.ok && kpisPayload.ok && kpisPayload.kpis) {
      setKpis(kpisPayload.kpis);
    }

    if (casesResponse.ok && casesPayload.ok && casesPayload.cases) {
      setCases(casesPayload.cases);
    }

    if (templatesResponse.ok && templatesPayload.ok && templatesPayload.templates) {
      setTemplates(templatesPayload.templates);
    }
  }

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

    try {
      const response = await fetch("/api/legal/diagnosis/start", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          contractId: diagnosisContractId || null,
        }),
      });

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

      if (!response.ok || !payload.ok || !payload.diagnosis) {
        setErrorMessage(payload.error ?? "No fue posible iniciar diagnostico.");
        return;
      }

      setDiagnosisId(payload.diagnosis.id);
      setDiagnosisStep(1);
      setDiagnosisRecommendation(payload.diagnosis.recommendation);
      setMessage("Diagnostico iniciado.");
    } catch {
      setErrorMessage("No fue posible iniciar diagnostico.");
    } finally {
      setIsBusy(false);
    }
  }

  async function submitDiagnosisStep(finalize = false) {
    if (!diagnosisId) {
      await startDiagnosis();
      return;
    }

    setIsBusy(true);
    setErrorMessage(null);

    try {
      const response = await fetch("/api/legal/diagnosis/answer", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          diagnosisId,
          stepIndex: diagnosisStep,
          finalize,
          answers: {
            breachType: diagnosisAnswers.breachType,
            processStage: diagnosisAnswers.processStage,
            evidenceLevel: diagnosisAnswers.evidenceLevel,
            urgency: diagnosisAnswers.urgency,
            objective: diagnosisAnswers.objective,
            amountAtRisk: diagnosisAnswers.amountAtRisk ? Number(diagnosisAnswers.amountAtRisk) : null,
            counterparty: diagnosisAnswers.counterparty,
            description: diagnosisAnswers.description,
          },
        }),
      });

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

      if (!response.ok || !payload.ok || !payload.diagnosis) {
        setErrorMessage(payload.error ?? "No fue posible registrar respuesta del diagnostico.");
        return;
      }

      setDiagnosisRecommendation(payload.diagnosis.recommendation);
      if (finalize) {
        setMessage("Diagnostico finalizado y caso legal generado.");
        setDiagnosisStep(4);
        await reloadDataset();
      } else {
        setDiagnosisStep((prev) => Math.min(4, prev + 1));
      }
    } catch {
      setErrorMessage("No fue posible registrar respuesta del diagnostico.");
    } finally {
      setIsBusy(false);
    }
  }

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

    try {
      const response = await fetch("/api/legal/cases", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          contractId: newCase.contractId || null,
          caseType: newCase.caseType,
          severity: newCase.severity,
          counterparty: newCase.counterparty,
          description: newCase.description,
          amountAtRisk: newCase.amountAtRisk ? Number(newCase.amountAtRisk) : null,
          status: newCase.status,
        }),
      });

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

      if (!response.ok || !payload.ok) {
        setErrorMessage(payload.error ?? "No fue posible crear el caso legal.");
        return;
      }

      setMessage("Caso legal creado.");
      setNewCase({
        contractId: prefilledContractId ?? "",
        caseType: "CONTRACT_BREACH",
        severity: "MEDIUM",
        counterparty: "",
        description: "",
        amountAtRisk: "",
        status: "OPEN",
      });
      await reloadDataset();
    } catch {
      setErrorMessage("No fue posible crear el caso legal.");
    } finally {
      setIsBusy(false);
    }
  }

  async function updateCaseStatus(caseId: string, status: LegalCaseView["status"]) {
    setErrorMessage(null);

    const resolvedAt = status === "RESOLVED" || status === "CLOSED" ? new Date().toISOString() : null;
    const response = await fetch(`/api/legal/cases/${encodeURIComponent(caseId)}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ status, resolvedAt }),
    });

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

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

    setMessage("Caso actualizado.");
    await reloadDataset();
  }

  async function loadEscalation(caseId: string) {
    if (!caseId) {
      setEscalation(null);
      return;
    }

    const response = await fetch(`/api/legal/escalation/${encodeURIComponent(caseId)}`);
    const payload = (await response.json().catch(() => ({}))) as ApiPayload;

    if (!response.ok || !payload.ok || !payload.escalation) {
      setErrorMessage(payload.error ?? "No fue posible cargar la ruta de escalada.");
      return;
    }

    setEscalation(payload.escalation);
  }

  async function toggleEscalationStep(caseId: string, stepKey: string, completed: boolean, notes: string) {
    const response = await fetch(`/api/legal/escalation/${encodeURIComponent(caseId)}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        routeStepKey: stepKey,
        completed,
        notes,
      }),
    });

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

    if (!response.ok || !payload.ok || !payload.escalation) {
      setErrorMessage(payload.error ?? "No fue posible actualizar la escalada.");
      return;
    }

    setEscalation(payload.escalation);
    setMessage("Escalada actualizada.");
  }

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

    try {
      const response = await fetch("/api/legal/documents/generate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          legalCaseId: documentDraft.legalCaseId || null,
          caseType: documentDraft.caseType,
          severity: documentDraft.severity,
          templateKey: documentDraft.templateKey || null,
          counterparty: documentDraft.counterparty,
          companyName: documentDraft.companyName,
          amountAtRisk: documentDraft.amountAtRisk ? Number(documentDraft.amountAtRisk) : null,
          description: documentDraft.description,
          objective: documentDraft.objective,
          title: documentDraft.title || null,
        }),
      });

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

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

      setGeneratedDocuments((prev) => [payload.document as { id: string; title: string; content: string; createdAt: string }, ...prev]);
      const warningText = payload.generation?.warnings?.join(" | ");
      setMessage(warningText ? `Escrito generado. ${warningText}` : "Escrito generado.");
    } catch {
      setErrorMessage("No fue posible generar el escrito.");
    } finally {
      setIsBusy(false);
    }
  }

  async function reloadDirectory() {
    const params = new URLSearchParams();
    if (directoryFilters.jurisdictionLevel) {
      params.set("jurisdictionLevel", directoryFilters.jurisdictionLevel);
    }
    if (directoryFilters.q.trim()) {
      params.set("q", directoryFilters.q.trim());
    }

    const response = await fetch(`/api/legal/directory${params.toString() ? `?${params.toString()}` : ""}`);
    const payload = (await response.json().catch(() => ({}))) as ApiPayload;

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

    setDirectory(payload.entities);
  }

  useEffect(() => {
    if (selectedEscalationCaseId) {
      void loadEscalation(selectedEscalationCaseId);
    }
  }, [selectedEscalationCaseId]);

  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]">Casos abiertos</p>
            <p className="mt-2 text-4xl font-semibold text-[#15294d]">{kpis.openCases}</p>
          </CardContent>
        </Card>

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

        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Monto en riesgo</p>
            <p className="mt-2 text-3xl font-semibold text-[#15294d]">{kpis.amountAtRisk.toLocaleString("es-MX")}</p>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Casos resueltos</p>
            <p className="mt-2 text-4xl font-semibold text-[#15294d]">{kpis.resolvedCases}</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="diagnosis"
        items={[
          {
            id: "diagnosis",
            label: "Diagnostico",
            content: (
              <Card>
                <CardContent className="space-y-3 py-5">
                  <p className="text-sm text-[#60718f]">Wizard de 4 pasos para sugerir severidad, tipo de caso y ruta de escalada.</p>
                  <p className="text-xs font-semibold text-[#415a82]">Paso {diagnosisStep} de 4</p>
                  <label className="space-y-1 text-xs font-semibold text-[#314764]">
                    Contrato vinculado (opcional)
                    <select
                      value={diagnosisContractId}
                      onChange={(event) => setDiagnosisContractId(event.target.value)}
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                      disabled={Boolean(diagnosisId)}
                    >
                      <option value="">Sin contrato</option>
                      {contractOptions.map((contract) => (
                        <option key={contract.id} value={contract.id}>
                          {contract.isPrefilled ? `${contract.label} (prefill)` : contract.label}
                        </option>
                      ))}
                    </select>
                  </label>

                  <div className="grid gap-2 md:grid-cols-2">
                    <label className="space-y-1 text-xs font-semibold text-[#314764]">
                      Tipo de incumplimiento
                      <select
                        value={diagnosisAnswers.breachType}
                        onChange={(event) => setDiagnosisAnswers((prev) => ({ ...prev, breachType: event.target.value }))}
                        className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                      >
                        <option value="contract_breach">Incumplimiento contractual</option>
                        <option value="payment_retention">Retencion de pagos</option>
                        <option value="unjust_sanction">Sancion injusta</option>
                        <option value="contract_dispute">Disputa contractual</option>
                      </select>
                    </label>

                    <label className="space-y-1 text-xs font-semibold text-[#314764]">
                      Estado procesal
                      <select
                        value={diagnosisAnswers.processStage}
                        onChange={(event) => setDiagnosisAnswers((prev) => ({ ...prev, processStage: event.target.value }))}
                        className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                      >
                        <option value="none">Sin proceso</option>
                        <option value="informal_notice">Aviso informal</option>
                        <option value="formal_notice">Requerimiento formal</option>
                        <option value="ongoing_claim">Reclamacion en curso</option>
                        <option value="trial">Via jurisdiccional</option>
                      </select>
                    </label>

                    <label className="space-y-1 text-xs font-semibold text-[#314764]">
                      Evidencia disponible
                      <select
                        value={diagnosisAnswers.evidenceLevel}
                        onChange={(event) => setDiagnosisAnswers((prev) => ({ ...prev, evidenceLevel: event.target.value }))}
                        className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                      >
                        <option value="none">Sin evidencia</option>
                        <option value="basic">Basica</option>
                        <option value="solid">Solida</option>
                        <option value="robust">Robusta</option>
                      </select>
                    </label>

                    <label className="space-y-1 text-xs font-semibold text-[#314764]">
                      Urgencia
                      <select
                        value={diagnosisAnswers.urgency}
                        onChange={(event) => setDiagnosisAnswers((prev) => ({ ...prev, urgency: event.target.value }))}
                        className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                      >
                        <option value="low">Baja</option>
                        <option value="medium">Media</option>
                        <option value="high">Alta</option>
                      </select>
                    </label>

                    <label className="space-y-1 text-xs font-semibold text-[#314764]">
                      Objetivo legal
                      <select
                        value={diagnosisAnswers.objective}
                        onChange={(event) => setDiagnosisAnswers((prev) => ({ ...prev, objective: event.target.value }))}
                        className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                      >
                        <option value="payment">Recuperar pago</option>
                        <option value="correction">Correccion</option>
                        <option value="challenge">Impugnacion</option>
                        <option value="mediation">Mediacion</option>
                      </select>
                    </label>

                    <label className="space-y-1 text-xs font-semibold text-[#314764]">
                      Monto en riesgo
                      <input
                        type="number"
                        value={diagnosisAnswers.amountAtRisk}
                        onChange={(event) => setDiagnosisAnswers((prev) => ({ ...prev, amountAtRisk: event.target.value }))}
                        className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                      />
                    </label>
                  </div>

                  <input
                    value={diagnosisAnswers.counterparty}
                    onChange={(event) => setDiagnosisAnswers((prev) => ({ ...prev, counterparty: event.target.value }))}
                    placeholder="Contraparte"
                    className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                  />

                  <textarea
                    value={diagnosisAnswers.description}
                    onChange={(event) => setDiagnosisAnswers((prev) => ({ ...prev, description: event.target.value }))}
                    placeholder="Descripcion del caso"
                    className="min-h-[110px] w-full rounded-lg border border-[#cfd8e7] px-3 py-2 text-sm"
                  />

                  <div className="flex flex-wrap gap-2">
                    <Button variant="secondary" onClick={() => submitDiagnosisStep(false)} disabled={isBusy}>
                      Guardar paso
                    </Button>
                    <Button onClick={() => submitDiagnosisStep(true)} disabled={isBusy}>
                      Finalizar y abrir caso
                    </Button>
                  </div>

                  {diagnosisRecommendation ? (
                    <div className="rounded-xl border border-[#ced9ec] bg-[#f4f8ff] p-3 text-sm text-[#2d4b7b]">
                      <p>
                        Sugerencia: {diagnosisRecommendation.suggestedCaseType} / {diagnosisRecommendation.suggestedSeverity}
                      </p>
                      <p className="mt-1">Ruta: {diagnosisRecommendation.suggestedRoute.map((item) => item.title).join(" -> ")}</p>
                      <p className="mt-1">Escritos: {diagnosisRecommendation.recommendedTemplates.join(", ")}</p>
                    </div>
                  ) : null}
                </CardContent>
              </Card>
            ),
          },
          {
            id: "cases",
            label: "Casos",
            content: (
              <div className="space-y-3">
                <Dialog triggerLabel="Nuevo Caso" title="Nuevo Caso" description="Registro manual de caso legal">
                  <div className="space-y-2">
                    <select
                      value={newCase.contractId}
                      onChange={(event) => setNewCase((prev) => ({ ...prev, contractId: event.target.value }))}
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                    >
                      <option value="">Sin contrato</option>
                      {contractOptions.map((contract) => (
                        <option key={contract.id} value={contract.id}>
                          {contract.isPrefilled ? `${contract.label} (prefill)` : contract.label}
                        </option>
                      ))}
                    </select>
                    <input
                      value={newCase.counterparty}
                      onChange={(event) => setNewCase((prev) => ({ ...prev, counterparty: event.target.value }))}
                      placeholder="Contraparte"
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                    />
                    <textarea
                      value={newCase.description}
                      onChange={(event) => setNewCase((prev) => ({ ...prev, description: event.target.value }))}
                      placeholder="Descripcion"
                      className="min-h-[90px] w-full rounded-lg border border-[#cfd8e7] px-3 py-2 text-sm"
                    />
                    <Button onClick={createCase} disabled={isBusy}>
                      Guardar caso
                    </Button>
                  </div>
                </Dialog>

                {cases.length === 0 ? <p className="text-sm text-[#60718f]">Sin casos registrados.</p> : null}

                {cases.map((item) => (
                  <article key={item.id} className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <p className="text-sm font-semibold text-[#1d335a]">{item.caseType}</p>
                      <span className={`inline-flex rounded-full border px-2 py-0.5 text-xs font-semibold ${severityTone(item.severity)}`}>{item.severity}</span>
                    </div>
                    <p className="mt-1 text-xs text-[#60718f]">{item.counterparty}</p>
                    <p className="mt-1 text-xs text-[#60718f]">{item.description}</p>
                    <div className="mt-2 flex flex-wrap items-center gap-2">
                      <select
                        value={item.status}
                        onChange={(event) => updateCaseStatus(item.id, event.target.value as LegalCaseView["status"])}
                        className="h-8 rounded-lg border border-[#cfd8e7] px-2 text-xs"
                      >
                        <option value="OPEN">OPEN</option>
                        <option value="IN_PROGRESS">IN_PROGRESS</option>
                        <option value="ESCALATED">ESCALATED</option>
                        <option value="RESOLVED">RESOLVED</option>
                        <option value="CLOSED">CLOSED</option>
                      </select>
                      <span className="text-xs text-[#60718f]">Abierto: {formatDate(item.openedAt)}</span>
                    </div>
                  </article>
                ))}
              </div>
            ),
          },
          {
            id: "escalation",
            label: "Escalada",
            content: (
              <div className="space-y-3">
                <select
                  value={selectedEscalationCaseId}
                  onChange={(event) => setSelectedEscalationCaseId(event.target.value)}
                  className="h-10 w-full rounded-lg border border-[#cfd8e7] bg-white px-3 text-sm"
                >
                  <option value="">Selecciona caso</option>
                  {cases.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.caseType} - {item.counterparty}
                    </option>
                  ))}
                </select>

                {currentEscalationCase && !escalation ? <Button variant="secondary" onClick={() => loadEscalation(currentEscalationCase.id)}>Cargar ruta</Button> : null}

                {escalation?.steps.map((step) => (
                  <article key={step.key} className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <div>
                        <p className="text-sm font-semibold text-[#1d335a]">{step.title}</p>
                        <p className="text-xs text-[#60718f]">Ventana estimada: {step.estimatedWindow}</p>
                        {step.requiresLawyer ? <p className="text-xs font-semibold text-[#9b4f2c]">Requiere abogado</p> : null}
                      </div>
                      <label className="inline-flex items-center gap-2 text-xs font-semibold text-[#314764]">
                        <input
                          type="checkbox"
                          checked={Boolean(step.completedAt)}
                          disabled={step.isBlocked}
                          onChange={(event) => {
                            if (!selectedEscalationCaseId) {
                              return;
                            }
                            void toggleEscalationStep(selectedEscalationCaseId, step.key, event.target.checked, step.notes ?? "");
                          }}
                        />
                        Completado
                      </label>
                    </div>
                    <ul className="mt-2 list-disc pl-5 text-xs text-[#60718f]">
                      {step.checklist.map((item) => (
                        <li key={`${step.key}-${item}`}>{item}</li>
                      ))}
                    </ul>
                  </article>
                ))}
              </div>
            ),
          },
          {
            id: "documents",
            label: "Escritos",
            content: (
              <div className="space-y-3">
                <Card>
                  <CardContent className="space-y-2 py-5">
                    <select
                      value={documentDraft.legalCaseId}
                      onChange={(event) => setDocumentDraft((prev) => ({ ...prev, legalCaseId: event.target.value }))}
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                    >
                      <option value="">Sin caso vinculado</option>
                      {cases.map((item) => (
                        <option key={item.id} value={item.id}>
                          {item.caseType} - {item.counterparty}
                        </option>
                      ))}
                    </select>

                    <select
                      value={documentDraft.templateKey}
                      onChange={(event) => setDocumentDraft((prev) => ({ ...prev, templateKey: event.target.value }))}
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                    >
                      <option value="">Plantilla automatica por tipo de caso</option>
                      {templates.map((template) => (
                        <option key={template.key} value={template.key}>
                          {template.title}
                        </option>
                      ))}
                    </select>

                    <input
                      value={documentDraft.counterparty}
                      onChange={(event) => setDocumentDraft((prev) => ({ ...prev, counterparty: event.target.value }))}
                      placeholder="Contraparte"
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                    />
                    <input
                      value={documentDraft.companyName}
                      onChange={(event) => setDocumentDraft((prev) => ({ ...prev, companyName: event.target.value }))}
                      placeholder="Empresa"
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                    />
                    <input
                      value={documentDraft.objective}
                      onChange={(event) => setDocumentDraft((prev) => ({ ...prev, objective: event.target.value }))}
                      placeholder="Objetivo legal"
                      className="h-10 w-full rounded-lg border border-[#cfd8e7] px-3 text-sm"
                    />
                    <textarea
                      value={documentDraft.description}
                      onChange={(event) => setDocumentDraft((prev) => ({ ...prev, description: event.target.value }))}
                      placeholder="Descripcion"
                      className="min-h-[110px] w-full rounded-lg border border-[#cfd8e7] px-3 py-2 text-sm"
                    />

                    <Button onClick={generateDocument} disabled={isBusy}>
                      Generar escrito
                    </Button>
                  </CardContent>
                </Card>

                {generatedDocuments.map((item) => (
                  <article key={item.id} className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                    <p className="text-sm font-semibold text-[#1d335a]">{item.title}</p>
                    <p className="mt-1 text-xs text-[#60718f]">{formatDate(item.createdAt)}</p>
                    <textarea readOnly value={item.content} className="mt-2 min-h-[160px] w-full rounded-lg border border-[#cfd8e7] p-2 text-xs" />
                  </article>
                ))}
              </div>
            ),
          },
          {
            id: "directory",
            label: "Directorio",
            content: (
              <div className="space-y-3">
                <div className="flex flex-wrap gap-2">
                  <select
                    value={directoryFilters.jurisdictionLevel}
                    onChange={(event) => setDirectoryFilters((prev) => ({ ...prev, jurisdictionLevel: event.target.value }))}
                    className="h-10 rounded-lg border border-[#cfd8e7] px-3 text-sm"
                  >
                    <option value="">Todas las jurisdicciones</option>
                    <option value="FEDERAL">FEDERAL</option>
                    <option value="STATE">STATE</option>
                    <option value="MUNICIPAL">MUNICIPAL</option>
                  </select>
                  <input
                    value={directoryFilters.q}
                    onChange={(event) => setDirectoryFilters((prev) => ({ ...prev, q: event.target.value }))}
                    placeholder="Buscar entidad"
                    className="h-10 min-w-[260px] rounded-lg border border-[#cfd8e7] px-3 text-sm"
                  />
                  <Button variant="secondary" onClick={reloadDirectory}>
                    Filtrar
                  </Button>
                </div>

                {directory.length === 0 ? <p className="text-sm text-[#60718f]">Sin entidades en el filtro actual.</p> : null}

                {directory.map((item) => (
                  <article key={item.id} className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                    <p className="text-sm font-semibold text-[#1d335a]">{item.name}</p>
                    <p className="mt-1 text-xs text-[#60718f]">{item.jurisdictionLevel} - {item.scopeTags.join(", ")}</p>
                    <p className="mt-1 text-xs text-[#60718f]">{item.websiteUrl ?? "Sin sitio web"}</p>
                  </article>
                ))}
              </div>
            ),
          },
        ]}
      />
    </div>
  );
}
