import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { updatePageAction } from "@/actions/pages";
import { Flash } from "@/components/admin/Flash";
import { PageForm } from "@/components/admin/PageForm";
import { requireAdmin } from "@/lib/auth/dal";
import { parseIdParam } from "@/lib/params";
import { getPageById } from "@/lib/services/pages";

export const metadata: Metadata = { title: "Edit page" };

export default async function EditPagePage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  await requireAdmin();
  const [{ id: rawId }, sp] = await Promise.all([params, searchParams]);

  const id = parseIdParam(rawId);
  if (id === null) notFound();

  const page = await getPageById(id);
  if (!page) notFound();

  return (
    <div>
      <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
        <h1 className="text-2xl font-bold tracking-tight text-ink-bright">Edit page</h1>
        <div className="flex items-center gap-4 text-sm">
          <Link
            href={`/admin/pages/${page.id}/preview`}
            className="text-ink-muted transition-colors hover:text-link"
          >
            Preview
          </Link>
          {page.status === "published" && (
            <Link
              href={`/pages/${page.slug}`}
              className="text-ink-muted transition-colors hover:text-link"
            >
              View on site
            </Link>
          )}
        </div>
      </div>

      {sp.saved === "1" && <Flash>Saved.</Flash>}

      <PageForm page={page} action={updatePageAction.bind(null, page.id)} />
    </div>
  );
}
