"use client";

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

/**
 * /reportes/[slug] — one report's runner page. The whole page is
 * data-driven from the catalog; if a slug isn't in the registry the
 * page shows a "not found" inline message.
 */
export default function ReporteRunnerPage({
  params,
  searchParams,
}: {
  params: { slug: string };
  searchParams?: Record<string, string | string[] | undefined>;
}) {
  return (
    <AppShell>
      <Runner slug={params.slug} searchParams={searchParams} />
    </AppShell>
  );
}

function Runner({
  slug,
  searchParams,
}: {
  slug: string;
  searchParams?: Record<string, string | string[] | undefined>;
}) {
  const [def, setDef] = useState<ReportDef | null>(null);
  const [missing, setMissing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    getReportCatalog()
      .then((c) => {
        const found = c.items.find((r) => r.slug === slug);
        if (found) setDef(found);
        else setMissing(true);
      })
      .catch((e) => setError(e?.message ?? "No se pudo cargar el reporte."));
  }, [slug]);

  if (error) {
    return (
      <>
        <BackLink />
        <div className="report-error">{error}</div>
      </>
    );
  }
  if (missing) {
    return (
      <>
        <BackLink />
        <div className="empty-inline">Reporte "{slug}" no encontrado.</div>
      </>
    );
  }
  if (!def) {
    return (
      <>
        <BackLink />
        <div className="empty-inline">Cargando reporte…</div>
      </>
    );
  }

  const initialParams: Record<string, string> = {};
  if (searchParams) {
    const allowed = new Set(def.params.map((p) => p.key));
    for (const [k, v] of Object.entries(searchParams)) {
      if (!allowed.has(k)) continue;
      const s = Array.isArray(v) ? v[0] : v;
      if (s) initialParams[k] = s;
    }
  }

  return (
    <>
      <div className="page-head rise">
        <p className="eyebrow">Reportes</p>
        <h1 className="page-title">{def.title}</h1>
        <p className="muted" style={{ marginTop: 6, maxWidth: 720 }}>
          {def.description}
        </p>
        {def.legacyName && (
          <p className="muted small" style={{ marginTop: 4 }}>
            Equivalente en Access: <code>{def.legacyName}</code>
          </p>
        )}
      </div>
      <ReportRunner def={def} initialParams={initialParams} />
    </>
  );
}

function BackLink() {
  return (
    <Link href="/reportes" className="back-link">
      ← Reportes
    </Link>
  );
}
