import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { PanelEditor } from "@/components/features/panels";
import { WebsiteSelect } from "@/components/ui/website-select";
import { canAnywhere } from "@/lib/authz/context";
import { AuthError } from "@/lib/authz/errors";
import { requireDashboard } from "@/lib/authz/guard";
import { getActiveSiteId, listAccessibleSites } from "@/lib/data/sites";
import { emptyArticle, emptySection } from "@/lib/blocks/layout";
import { getNewPanelEditorData } from "@/lib/services/panels";

export const metadata: Metadata = { title: "Add panel" };
export const dynamic = "force-dynamic";

/** Add Panel = the same editor in create mode; nothing is stored until "Create Panel". */
export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const ctx = await requireDashboard("admin");
  if (!canAnywhere(ctx, "content.manage")) notFound();
  const requested = (await searchParams).location;
  const sites = await listAccessibleSites(ctx);
  const siteId = await getActiveSiteId(sites);
  if (!siteId) notFound();
  let data;
  try {
    data = await getNewPanelEditorData(siteId);
  } catch (e) {
    if (e instanceof AuthError) notFound();
    throw e;
  }
  const preset = typeof requested === "string" && data.locations.some((l) => l.key === requested) ? requested : "";
  return (
    <PanelEditor
      key={`new:${siteId}`}
      panel={null}
      presetLocation={preset}
      siteId={data.site.id}
      siteName={data.site.name}
      content={{ v: 2, sections: [emptySection([emptyArticle()])] }}
      pages={data.pages}
      forms={data.forms}
      events={data.events}
      locations={data.locations}
      canManage
      websiteField={ctx.isSuperAdmin ? <WebsiteSelect sites={sites} activeSiteId={siteId} /> : undefined}
    />
  );
}
