import Link from "next/link";
import { notFound } from "next/navigation";
import { ReportView } from "@/components/features/reports/report-view";
import { Card, EmptyState, PageHeader, buttonClass } from "@/components/ui";
import { AuthError } from "@/lib/authz/errors";
import { UserError } from "@/lib/actions/result";
import { reportConfigSchema } from "@/lib/reports/query";
import { listSavedFilters, runReport } from "@/lib/services/report-builder";
import { reportsBase, reportsStart, type ReportsKind } from "./reports-shared";

const first = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v);

export async function ReportsRunScreen({ kind, searchParams }: { kind: ReportsKind; searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const s = await reportsStart(kind, "Report");
  if (s.siteId === null) return s.empty;
  const sp = await searchParams;
  const entity = first(sp.entity)?.slice(0, 80) ?? "";
  const back = <Link href={`${reportsBase(kind)}/scheduled`} className={buttonClass("secondary")}>All report types</Link>;
  let rawConfig: unknown = {};
  const saved = first(sp.filter);
  try {
    if (saved && /^[A-Za-z0-9_-]{1,40}$/.test(saved)) {
      const f = (await listSavedFilters(s.siteId)).find((x) => x.id === saved && x.entity === entity);
      if (!f) notFound();
      rawConfig = f.config;
    } else rawConfig = JSON.parse(first(sp.config) || "{}");
  } catch (e) {
    if (e instanceof AuthError) notFound();
    if (!(e instanceof SyntaxError)) throw e;
    rawConfig = {};
  }
  const parsed = reportConfigSchema.safeParse(rawConfig);
  let result, problem = "";
  try {
    result = await runReport(s.siteId, entity, parsed.success ? parsed.data : {}, Number(first(sp.page)) || 1, Number(first(sp.perPage)) || 25);
  } catch (e) {
    if (e instanceof AuthError) notFound();
    if (e instanceof UserError) problem = e.message; else throw e;
  }
  if (!result) return (<><PageHeader title="Report" actions={back} /><Card><EmptyState title="This report cannot be shown" description={problem || "Choose a report type first."} /></Card></>);
  return (
    <>
      <PageHeader title={result.entity.label} description={`${result.total} row${result.total === 1 ? "" : "s"}`} actions={back} />
      <ReportView siteId={s.siteId} base={`${reportsBase(kind)}/scheduled`} result={{ ...result, rows: result.rows as Record<string, string | number>[] }} />
    </>
  );
}
