"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { getReportCatalog } from "@/lib/api";
import type { ReportCatalog, ReportDef, ReportDomain } from "@/lib/types";

/**
 * The /reportes catalog. Index of every registered report, grouped by
 * domain (matches the main nav). Discovery layer for the 280+ reports
 * the system will eventually surface; for now we ship 6 in v1.
 */
export default function ReportesPage() {
  return (
    <AppShell>
      <ReportesCatalog />
    </AppShell>
  );
}

const DOMAIN_LABEL: Record<ReportDomain, string> = {
  clientes: "Clientes",
  polizas: "Pólizas",
  servicios: "Servicios",
  "estado-cuenta": "Estado de cuenta",
  chequera: "Chequera",
};

const DOMAIN_ORDER: ReportDomain[] = [
  "clientes",
  "estado-cuenta",
  "polizas",
  "servicios",
  "chequera",
];

function ReportesCatalog() {
  const [catalog, setCatalog] = useState<ReportCatalog | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    getReportCatalog()
      .then(setCatalog)
      .catch((e) => setError(e?.message ?? "No se pudo cargar el catálogo."));
  }, []);

  const grouped = new Map<ReportDomain, ReportDef[]>();
  if (catalog) {
    for (const r of catalog.items) {
      const list = grouped.get(r.domain) ?? [];
      list.push(r);
      grouped.set(r.domain, list);
    }
  }

  return (
    <>
      <div className="page-head rise">
        <p className="eyebrow">Reportes</p>
        <h1 className="page-title">Catálogo de reportes</h1>
        <p className="muted" style={{ marginTop: 6, maxWidth: 640 }}>
          {catalog
            ? `${catalog.items.length} reportes disponibles. Cada uno corre como consulta sobre el esquema actual — los filtros y totales se recalculan en vivo.`
            : "Cargando…"}
        </p>
      </div>

      {error && <div className="report-error">{error}</div>}

      <div className="report-catalog">
        {DOMAIN_ORDER.filter((d) => grouped.has(d)).map((d) => (
          <section key={d} className="report-catalog-group">
            <h2 className="report-catalog-title">{DOMAIN_LABEL[d]}</h2>
            <ul className="report-catalog-list">
              {(grouped.get(d) ?? []).map((r) => (
                <li key={r.slug} className="report-catalog-item">
                  <Link href={`/reportes/${r.slug}`} className="report-catalog-link">
                    <div className="report-catalog-item-title">{r.title}</div>
                    <div className="report-catalog-item-desc">{r.description}</div>
                    <div className="report-catalog-item-meta">
                      {r.legacyName && (
                        <span className="report-catalog-tag">
                          Legacy: {r.legacyName}
                        </span>
                      )}
                      <span className="report-catalog-tag muted">
                        {r.format === "statement" ? "Estado de cuenta" : "Tabular"}
                      </span>
                    </div>
                  </Link>
                </li>
              ))}
            </ul>
          </section>
        ))}
      </div>
    </>
  );
}
