"use client";

import { useEffect, useState } from "react";
import { dateTimeCL } from "../lib/datetime";
import { userMessage } from "../lib/messages";

const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL || "/api/v1";
type Row = Record<string, unknown>;
type Overview = { version: string; estado: string; generado_en: string; controles: Row[]; alertas: Row[]; ejecuciones: Row[]; dominios: Row[] };

function value(input: unknown) { return input === null || input === undefined ? "" : String(input); }
function message(detail: unknown, fallback: string) {
  if (typeof detail === "string") return detail;
  if (detail && typeof detail === "object" && "message" in detail) return String((detail as { message: unknown }).message);
  return fallback;
}

export default function OperationsManagement({ csrf, notify }: { csrf: () => Promise<string>; notify: (text: string) => void }) {
  const [data, setData] = useState<Overview | null>(null), [busy, setBusy] = useState(true), [detail, setDetail] = useState<Row | null>(null);
  async function request(path = "", options: RequestInit = {}) {
    const response = await fetch(`${apiBase}/panel/admin/operations${path}`, { credentials: "include", cache: "no-store", ...options });
    if (response.status === 401) { sessionStorage.removeItem("documenta:csrf"); window.location.replace("/acceso?motivo=sesion-expirada"); throw new Error("Sesión expirada"); }
    const body = await response.json();
    if (!response.ok) throw new Error(message(body.detail, "No fue posible consultar la operación."));
    return body;
  }
  async function load() { setBusy(true); try { setData(await request() as Overview); } catch (error) { notify(userMessage(error, "No fue posible cargar la operación.")); } finally { setBusy(false); } }
  useEffect(() => {
    let active = true;
    void (async () => {
      try {
        const response = await fetch(`${apiBase}/panel/admin/operations`, { credentials: "include", cache: "no-store" });
        if (response.status === 401) { window.location.replace("/acceso?motivo=sesion-expirada"); return; }
        const body = await response.json();
        if (!response.ok) throw new Error(message(body.detail, "No fue posible cargar la operación."));
        if (active) setData(body as Overview);
      } catch (error) { if (active) notify(userMessage(error, "No fue posible cargar la operación.")); }
      finally { if (active) setBusy(false); }
    })();
    return () => { active = false; };
  }, [notify]);
  async function run() {
    setBusy(true);
    try {
      const token = await csrf();
      const result = await request("/run", { method: "POST", headers: { "X-CSRF-Token": token } });
      notify(`Control ${value(result.estado).toLowerCase()}: ${value(result.resumen)}`);
      await load();
    } catch (error) { notify(userMessage(error, "No fue posible ejecutar los controles.")); }
    finally { setBusy(false); }
  }
  async function openRun(uuid: string) { setBusy(true); try { setDetail(await request(`/runs/${uuid}`)); } catch (error) { notify(userMessage(error, "No fue posible abrir la ejecución.")); } finally { setBusy(false); } }
  const controls = data?.controles || [], alerts = data?.alertas || [], runs = data?.ejecuciones || [];
  return <div className="operations-admin">
    <section className={`panel-card operations-hero state-${value(data?.estado).toLowerCase()}`}><div><span className="section-kicker">H12 · RELEASE CANDIDATE</span><h2>Centro de Operaciones</h2><p>Salud de plataforma, colas, conectores, respaldo y controles de aceptación en una vista.</p></div><div className="operations-hero-state"><small>Estado integral</small><strong>{value(data?.estado || "CARGANDO")}</strong><span>API {value(data?.version || "1.20.0")}</span></div><button className="button button-primary" disabled={busy} onClick={() => void run()}>{busy ? "Comprobando…" : "Ejecutar controles"}</button></section>
    <section className="operations-control-grid">{controls.map((row) => <article className={`panel-card state-${value(row.estado).toLowerCase()}`} key={value(row.codigo)}><header><span>{value(row.categoria)}</span><b>{value(row.estado)}</b></header><h3>{value(row.componente)}</h3><p>{value(row.detalle)}</p><small>{value(row.duracion_ms)} ms · {value(row.codigo)}</small></article>)}</section>
    <div className="operations-two"><section className="panel-card"><div className="verification-admin-heading"><div><h2>Alertas</h2><p>Se abren y resuelven con cada ejecución persistida.</p></div><button className="table-action" disabled={busy} onClick={() => void load()}>Actualizar</button></div>{alerts.length ? <div className="operations-alerts">{alerts.map((row) => <article key={value(row.codigo)} className={`state-${value(row.estado).toLowerCase()}`}><div><b>{value(row.severidad)} · {value(row.componente)}</b><p>{value(row.resumen)}</p><small>{value(row.codigo)} · {Number(row.ocurrencias || 0)} ocurrencia(s)</small></div><span>{value(row.estado)}</span></article>)}</div> : <div className="panel-empty">No hay alertas registradas.</div>}</section>
      <section className="panel-card"><h2>Dominios controlados</h2><p className="operations-copy">La aceptación externa prueba cada host mediante HTTPS y valida su destino esperado.</p><div className="operations-domains">{(data?.dominios || []).map((row) => <div key={value(row.host)}><span className="operations-dot"/><div><b>{value(row.host)}</b><small>{value(row.rol)}</small></div></div>)}</div></section></div>
    <section className="panel-card"><div className="verification-admin-heading"><div><h2>Evidencia de aceptación</h2><p>Ejecuciones persistidas con versión, resultado y conteo de controles.</p></div></div><div className="panel-table-wrap"><table><thead><tr><th>Fecha</th><th>Tipo</th><th>Versión</th><th>Estado</th><th>Resultado</th><th/></tr></thead><tbody>{runs.map((row) => <tr key={value(row.uuid)}><td>{dateTimeCL(row.iniciada_en)}</td><td>{value(row.tipo)}</td><td>{value(row.version_aplicacion)}</td><td><b>{value(row.estado)}</b></td><td>{value(row.controles_ok)}/{value(row.controles_total)} OK</td><td><button className="table-action" onClick={() => void openRun(value(row.uuid))}>Detalle</button></td></tr>)}</tbody></table></div>{!runs.length && <div className="panel-empty">Ejecuta el primer control integral.</div>}</section>
    {detail && <div className="admin-modal-backdrop"><section className="admin-modal admin-modal-large"><header><div><span className="section-kicker">EVIDENCIA H12</span><h2>{value((detail.ejecucion as Row).estado)}</h2></div><button className="modal-close" onClick={() => setDetail(null)}>×</button></header><div className="admin-modal-content operations-detail">{((detail.controles || []) as Row[]).map((row) => <article key={value(row.codigo)}><header><strong>{value(row.componente)}</strong><b>{value(row.estado)}</b></header><p>{value(row.detalle)}</p><small>{value(row.codigo)} · {value(row.duracion_ms)} ms</small>{Boolean(row.evidencia) && <pre>{JSON.stringify(row.evidencia, null, 2)}</pre>}</article>)}</div></section></div>}
  </div>;
}
