import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";

import { Container } from "@/components/Container";
import { PageHeader } from "@/components/PageHeader";
import { BuilderWizard } from "@/components/consentiq/BuilderWizard";
import { getPublicProcedureBySlug } from "@/lib/consentiq/queries";
import { getProcedure } from "@/data/consentiq/procedures";

type Params = { procedureSlug: string };

export const dynamic = "force-dynamic";

async function loadProcedure(slug: string) {
  const fromDb = await getPublicProcedureBySlug(slug).catch(() => null);
  return fromDb ?? getProcedure(slug) ?? null;
}

export async function generateMetadata({
  params,
}: {
  params: Promise<Params>;
}): Promise<Metadata> {
  const { procedureSlug } = await params;
  const procedure = await loadProcedure(procedureSlug);
  if (!procedure) return { title: "Procedure not found" };
  return {
    title: `${procedure.name} · ConsentIQ builder`,
    description: `Build a draft consent for ${procedure.name} using the ConsentIQ template.`,
  };
}

export default async function BuilderPage({
  params,
}: {
  params: Promise<Params>;
}) {
  const { procedureSlug } = await params;
  const procedure = await loadProcedure(procedureSlug);
  if (!procedure) notFound();

  return (
    <>
      <PageHeader
        eyebrow={`ConsentIQ · ${procedure.region}`}
        title={procedure.name}
        lede={procedure.summary}
      />
      <Container className="pb-14 md:pb-16">
        <div className="mb-6 text-[13px] text-[var(--color-slate)]">
          <Link
            href="/products/consentiq/procedures"
            className="font-semibold text-[var(--color-blue)] hover:text-[var(--color-blue-deep)]"
          >
            ← All procedures
          </Link>
        </div>
        <BuilderWizard procedure={procedure} />
      </Container>
    </>
  );
}
