import { notFound } from "next/navigation";
import { RapportsPanel } from "@/components/features/rapports/rapports-panel";
import { Card, EmptyState, PageHeader, buttonClass } from "@/components/ui";
import { canAnywhere, type DashboardKind } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { AuthError } from "@/lib/authz/errors";
import { getActiveSiteId, listAccessibleSites } from "@/lib/data/sites";
import { getRapportData } from "@/lib/services/rapports";

export async function RapportsScreen({ kind }: { kind: Extract<DashboardKind, "admin"> }) {
  const ctx = await requireDashboard(kind);
  if (!canAnywhere(ctx, "reports.read")) notFound();
  const siteId = await getActiveSiteId(await listAccessibleSites(ctx));
  if (!siteId) return (<><PageHeader title="Rapports" /><Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown)." /></Card></>);
  let d;
  try { d = await getRapportData(siteId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  return (
    <>
      <PageHeader title="Rapports" description="Requests from visitors to meet exhibitors and speakers." actions={<a href={`/api/reports/rapports?siteId=${siteId}`} className={buttonClass("secondary")} download>Export Rapports (CSV)</a>} />
      <RapportsPanel siteId={siteId} publicPath="/rapport" options={d.options} canDecide={d.canDecide} canConfigure={d.canConfigure} rows={d.rows.map((r) => ({ ...r, createdAt: r.createdAt.toISOString() }))} />
      {d.truncated ? <p className="mt-3 text-xs text-muted-foreground">Showing the most recent 2,000 requests.</p> : null}
    </>
  );
}
