"use client";

import { useState } from "react";
import { Tabs } from "@/components/ui/tabs";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import type { M7Dataset } from "@/lib/compliance/types";

type ComplianceAlertsViewProps = {
  dataset: M7Dataset;
};

type M7AiPlaybook = {
  predictedIncidents: {
    title: string;
    likelihood: "alta" | "media" | "baja";
    impact: "alto" | "medio" | "bajo";
    timeHorizon: string;
  }[];
  priorityOrder: string[];
  preventiveActions: {
    action: string;
    ownerSuggestion: string;
    targetDate: string;
  }[];
  escalationAdvice: string[];
  confidence: "low" | "medium" | "high";
};

function toneClass(tone: "neutral" | "success" | "warning" | "danger") {
  if (tone === "success") {
    return "border-[#b9e6cd] bg-[#eaf9f1] text-[#1f8b63]";
  }

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

  if (tone === "danger") {
    return "border-[#f1c7ce] bg-[#fff1f4] text-[#b03f4f]";
  }

  return "border-[#d8e1ef] bg-[#f4f7fb] text-[#51688f]";
}

function severityClass(severity: "high" | "medium" | "low") {
  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 formatDateTime(value: string) {
  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",
  });
}

export function ComplianceAlertsView({ dataset }: ComplianceAlertsViewProps) {
  const [isLoadingAiPlaybook, setIsLoadingAiPlaybook] = useState(false);
  const [aiPlaybook, setAiPlaybook] = useState<M7AiPlaybook | null>(null);
  const [aiSuggestionId, setAiSuggestionId] = useState<string | null>(null);
  const [aiFeedback, setAiFeedback] = useState<string | null>(null);
  const [aiError, setAiError] = useState<string | null>(null);

  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 generateAiPlaybook() {
    setIsLoadingAiPlaybook(true);
    setAiError(null);
    setAiFeedback(null);

    try {
      const response = await fetch("/api/compliance/m7/ai/playbook", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ dataset }),
      });

      const payload = (await response.json().catch(() => ({}))) as {
        ok?: boolean;
        error?: string;
        predictedIncidents?: M7AiPlaybook["predictedIncidents"];
        priorityOrder?: M7AiPlaybook["priorityOrder"];
        preventiveActions?: M7AiPlaybook["preventiveActions"];
        escalationAdvice?: M7AiPlaybook["escalationAdvice"];
        confidence?: M7AiPlaybook["confidence"];
        suggestionId?: string;
      };

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

      setAiPlaybook({
        predictedIncidents: payload.predictedIncidents ?? [],
        priorityOrder: payload.priorityOrder ?? [],
        preventiveActions: payload.preventiveActions ?? [],
        escalationAdvice: payload.escalationAdvice ?? [],
        confidence: payload.confidence ?? "low",
      });
      setAiSuggestionId(payload.suggestionId ?? null);
      setAiFeedback("Plan IA generado.");
    } catch {
      setAiError("No fue posible generar plan IA.");
    } finally {
      setIsLoadingAiPlaybook(false);
    }
  }

  const isEmpty =
    dataset.kpis.activeLicitations === 0 &&
    dataset.tabs.plazos.length === 0 &&
    dataset.tabs.alertas.length === 0 &&
    dataset.tabs.checklist.length === 0;

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

        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Tasa de completitud</p>
            <p className="mt-2 text-4xl font-semibold text-[#15294d]">{dataset.kpis.completionRate}%</p>
          </CardContent>
        </Card>

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

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

      <section className="grid gap-3 md:grid-cols-4">
        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Consultadas</p>
            <p className="mt-2 text-3xl font-semibold text-[#15294d]">{dataset.m3States.consulted}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Me interesa</p>
            <p className="mt-2 text-3xl font-semibold text-[#15294d]">{dataset.m3States.interested}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Activas M5</p>
            <p className="mt-2 text-3xl font-semibold text-[#15294d]">{dataset.m3States.active}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-xs font-semibold uppercase tracking-[0.08em] text-[#60718f]">Nuevas M3</p>
            <p className="mt-2 text-3xl font-semibold text-[#15294d]">{dataset.m3States.new}</p>
          </CardContent>
        </Card>
      </section>

      {isEmpty ? (
        <Card className="border-dashed border-[#cfd8e6] bg-[#fbfdff]">
          <CardContent className="py-16 text-center">
            <p className="text-3xl font-semibold text-[#162748] [font-family:var(--font-display)]">Sin alertas de cumplimiento</p>
            <p className="mt-2 text-base text-[#5f7090]">Cuando tengas procesos activos en M5 y fechas detectadas, este tablero mostrara riesgos y vencimientos.</p>
          </CardContent>
        </Card>
      ) : null}

      {aiError ? <p className="rounded-lg border border-[#f1c7ce] bg-[#fff1f4] px-3 py-2 text-sm text-[#b03f4f]">{aiError}</p> : null}
      {aiFeedback ? <p className="rounded-lg border border-[#b9e6cd] bg-[#eaf9f1] px-3 py-2 text-sm text-[#1f8b63]">{aiFeedback}</p> : null}

      <Tabs
        defaultTab="plazos"
        items={[
          {
            id: "plazos",
            label: "Plazos",
            content: (
              <div className="space-y-2">
                {dataset.tabs.plazos.length === 0 ? <p className="text-sm text-[#60718f]">Sin plazos detectables para los proximos dias.</p> : null}
                {dataset.tabs.plazos.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.title}</p>
                      <span className={`inline-flex rounded-full border px-2 py-0.5 text-xs font-semibold ${item.status === "overdue" ? "border-[#f1c7ce] bg-[#fff1f4] text-[#b03f4f]" : "border-[#d8e1ef] bg-[#f4f7fb] text-[#51688f]"}`}>
                        {item.status === "overdue" ? "Vencido" : "Programado"}
                      </span>
                    </div>
                    <p className="mt-1 text-xs text-[#60718f]">{item.description}</p>
                    <p className="mt-1 text-xs font-semibold text-[#334d77]">{formatDateTime(item.dueAt)}</p>
                  </article>
                ))}
              </div>
            ),
          },
          {
            id: "alertas",
            label: "Alertas",
            content: (
              <div className="space-y-2">
                {dataset.tabs.alertas.length === 0 ? <p className="text-sm text-[#60718f]">Sin alertas activas.</p> : null}
                {dataset.tabs.alertas.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.title}</p>
                      <span className={`inline-flex rounded-full border px-2 py-0.5 text-xs font-semibold ${severityClass(item.severity)}`}>{item.severity}</span>
                    </div>
                    <p className="mt-1 text-xs text-[#60718f]">{item.description}</p>
                    {item.dueAt ? <p className="mt-1 text-xs font-semibold text-[#334d77]">{formatDateTime(item.dueAt)}</p> : null}
                  </article>
                ))}
              </div>
            ),
          },
          {
            id: "checklist",
            label: "Checklist",
            content: (
              <div className="space-y-2">
                {dataset.tabs.checklist.length === 0 ? <p className="text-sm text-[#60718f]">No hay procesos activos para checklist.</p> : null}
                {dataset.tabs.checklist.map((item) => (
                  <article key={item.proposalId} className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                    <p className="text-sm font-semibold text-[#1d335a]">{item.proposalTitle}</p>
                    <p className="mt-1 text-xs text-[#60718f]">
                      Obligatorios resueltos: {item.mandatoryResolved}/{item.mandatoryTotal} ({item.completionRate}%)
                    </p>
                    <p className="mt-1 text-xs text-[#60718f]">Firma: {item.signaturePolicyStatus.replaceAll("_", " ")}</p>
                  </article>
                ))}
              </div>
            ),
          },
          {
            id: "panel-kpi",
            label: "Panel KPI",
            content: (
              <div className="grid gap-2 md:grid-cols-2">
                {dataset.tabs.panelKpi.map((item) => (
                  <article key={item.id} className={`rounded-xl border p-3 ${toneClass(item.tone)}`}>
                    <p className="text-xs font-semibold uppercase tracking-[0.08em]">{item.label}</p>
                    <p className="mt-1 text-2xl font-semibold">{item.value}</p>
                  </article>
                ))}
              </div>
            ),
          },
          {
            id: "plan-ia",
            label: "Plan IA",
            content: (
              <div className="space-y-3">
                <div className="flex flex-wrap gap-2">
                  <Button type="button" variant="secondary" disabled={isLoadingAiPlaybook} onClick={() => void generateAiPlaybook()}>
                    {isLoadingAiPlaybook ? "Generando plan IA..." : "Generar plan IA"}
                  </Button>
                  {aiPlaybook ? (
                    <Button
                      type="button"
                      variant="secondary"
                      onClick={() => {
                        void setSuggestionDecision("dismiss");
                        setAiPlaybook(null);
                        setAiFeedback("Plan IA descartado.");
                      }}
                    >
                      Descartar plan IA
                    </Button>
                  ) : null}
                </div>

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

                {aiPlaybook ? (
                  <>
                    <article className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                      <p className="text-sm font-semibold text-[#1d335a]">Incidentes predichos</p>
                      <ul className="mt-2 space-y-2 text-xs text-[#60718f]">
                        {aiPlaybook.predictedIncidents.map((incident) => (
                          <li key={`${incident.title}-${incident.timeHorizon}`} className="rounded-lg border border-[#e4ebf6] px-2 py-1">
                            <p className="font-semibold text-[#233b62]">{incident.title}</p>
                            <p>
                              Probabilidad {incident.likelihood} · Impacto {incident.impact} · Horizonte {incident.timeHorizon}
                            </p>
                          </li>
                        ))}
                      </ul>
                    </article>

                    <article className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                      <p className="text-sm font-semibold text-[#1d335a]">Orden de prioridad</p>
                      <ol className="mt-2 space-y-1 text-xs text-[#60718f]">
                        {aiPlaybook.priorityOrder.map((item, index) => (
                          <li key={`${item}-${index}`}>
                            {index + 1}. {item}
                          </li>
                        ))}
                      </ol>
                    </article>

                    <article className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                      <p className="text-sm font-semibold text-[#1d335a]">Acciones preventivas</p>
                      <ul className="mt-2 space-y-2 text-xs text-[#60718f]">
                        {aiPlaybook.preventiveActions.map((action) => (
                          <li key={`${action.action}-${action.ownerSuggestion}`} className="rounded-lg border border-[#e4ebf6] px-2 py-1">
                            <p className="font-semibold text-[#233b62]">{action.action}</p>
                            <p>
                              Responsable sugerido: {action.ownerSuggestion} · Fecha objetivo: {action.targetDate}
                            </p>
                          </li>
                        ))}
                      </ul>
                    </article>

                    <article className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                      <p className="text-sm font-semibold text-[#1d335a]">Recomendaciones de escalamiento</p>
                      <ul className="mt-2 space-y-1 text-xs text-[#60718f]">
                        {aiPlaybook.escalationAdvice.map((item) => (
                          <li key={item}>- {item}</li>
                        ))}
                      </ul>
                      <div className="mt-3">
                        <Button
                          type="button"
                          size="sm"
                          onClick={() => {
                            void setSuggestionDecision("accept");
                            setAiFeedback("Plan IA marcado como aceptado.");
                          }}
                        >
                          Aceptar plan IA
                        </Button>
                      </div>
                    </article>
                  </>
                ) : null}
              </div>
            ),
          },
        ]}
      />
    </div>
  );
}
