import Link from "next/link";
import { notFound } from "next/navigation";
import { NewPageEditorScreen } from "@/components/features/page-editor/editor-screen";
import { PageHeader } from "@/components/ui";
import { can, type DashboardKind } from "@/lib/authz/context";
import { requireDashboard } from "@/lib/authz/guard";
import { getActiveSiteId, listAccessibleSites } from "@/lib/data/sites";
import { db } from "@/lib/db";

/** New page = the same editor as editing, in create mode. Nothing is stored until "Create Page". */
export async function NewPageScreen({ kind, searchParams }: { kind: Extract<DashboardKind, "admin" | "editor">; searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const ctx = await requireDashboard(kind);
  const sites = await listAccessibleSites(ctx);
  const full = await db.site.findMany({ where: { id: { in: sites.map((s) => s.id) } }, select: { id: true, name: true, organizationId: true } });
  const allowed = full.filter((s) => can(ctx, "pages.create", { siteId: s.id, siteOrganizationId: s.organizationId }));
  if (allowed.length === 0) notFound();
  const base = `/dashboard/${kind}` as const;

  const requested = (await searchParams).site;
  const requestedId = typeof requested === "string" ? requested : undefined;
  const chosen = allowed.find((s) => s.id === requestedId)?.id ?? (allowed.length === 1 ? allowed[0]!.id : await getActiveSiteId(allowed));
  if (chosen) return <NewPageEditorScreen base={base} siteId={chosen} websites={ctx.isSuperAdmin ? sites : undefined} />;

  return (
    <>
      <PageHeader title="New page" description="Choose the website this page belongs to." />
      <ul className="grid max-w-xl gap-3">
        {allowed.map((s) => (
          <li key={s.id}>
            <Link href={`${base}/pages/new?site=${encodeURIComponent(s.id)}`} className="block rounded-2xl bg-white p-4 text-sm font-bold shadow-sm ring-1 ring-border hover:ring-2 hover:ring-primary">{s.name}</Link>
          </li>
        ))}
      </ul>
    </>
  );
}
