import { notFound } from "next/navigation";
import { BarChart } from "@/components/charts/bar-chart";
import { Card, EmptyState, PageHeader, StatCard, 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 { formatBytes } from "@/lib/utils";
import { getSiteReport } from "@/lib/services/reports";

export async function ReportsScreen({ 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="Reports" /><Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown)." /></Card></>);
  let r;
  try { r = await getSiteReport(siteId); } catch (e) { if (e instanceof AuthError) notFound(); throw e; }
  const total = (rows: { value: number }[]) => rows.reduce((a, b) => a + b.value, 0);
  const periodTotal = r.submissionsPerDay.reduce((a, b) => a + b.count, 0);
  return (
    <>
      <PageHeader title="Reports" description={`${r.site.name} · figures are counted from your data`} actions={<a href={`/api/reports/submissions?siteId=${siteId}`} className={buttonClass("secondary")} download>Export submissions per day (CSV)</a>} />
      <div className="mb-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard label="Pages" value={String(total(r.pagesByStatus))} />
        <StatCard label={`Form submissions (${r.windowDays} days)`} value={String(periodTotal)} />
        <StatCard label="Media" value={`${r.media.files} · ${formatBytes(r.media.bytes)}`} />
        <StatCard label="Mean ticket resolution" value={r.meanResolutionHours === null ? "No resolved tickets" : `${r.meanResolutionHours} h`} />
      </div>
      <div className="grid gap-4 lg:grid-cols-2">
        <Card className="p-4"><BarChart title={`Form submissions per day (last ${r.windowDays} days, excluding spam)`} data={r.submissionsPerDay.map((d) => ({ label: d.day, value: d.count }))} />{r.submissionsTruncated ? <p className="mt-2 text-xs text-muted-foreground">Showing the most recent 20,000 submissions only.</p> : null}</Card>
        <Card className="p-4"><BarChart title="Pages by status" data={r.pagesByStatus} /></Card>
        <Card className="p-4"><BarChart title="Support tickets by status" data={r.ticketsByStatus} /></Card>
        <Card className="p-4"><BarChart title="Submissions by status" data={r.submissionsByStatus} /></Card>
      </div>
      <Card className="mt-4">
        <h2 className="px-4 pt-4 text-sm font-semibold">Content libraries</h2>
        {r.contentByType.length === 0 ? <p className="p-4 text-sm text-muted-foreground">No library content yet.</p> : (
          <table className="w-full text-left text-sm"><thead className="border-b border-border text-xs text-muted-foreground"><tr><th className="px-4 py-2 font-medium">Library</th><th className="px-4 py-2 font-medium">Published</th><th className="px-4 py-2 font-medium">Total</th></tr></thead>
            <tbody className="divide-y divide-border">{r.contentByType.map((c) => <tr key={c.label}><td className="px-4 py-2 capitalize">{c.label}</td><td className="px-4 py-2">{c.published}</td><td className="px-4 py-2">{c.total}</td></tr>)}</tbody></table>
        )}
      </Card>
      <p className="mt-4 text-xs text-muted-foreground">Visitor traffic is not shown here: this platform does not collect it. Use the analytics provider configured under SEO & settings.</p>
    </>
  );
}
