import { redirect } from "next/navigation";

import { MotionFade } from "@/components/motion-fade";
import { FlashMessage } from "@/components/root/flash-message";
import { PortfolioProjectForm } from "@/components/root/portfolio-project-form";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMediaOptions } from "@/lib/media";
import { getActivePortfolioCategories } from "@/lib/portfolio";

import { saveProjectAction } from "../../actions";

export const dynamic = "force-dynamic";

const copy = {
  title: "Neues Portfolio Projekt",
  subtitle: "Projekt mit Kategorie, Abschnitten und Dateien anlegen.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "Settings",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

type RootNewPortfolioProjectPageProps = {
  searchParams?: {
    error?: string;
  };
};

export default async function RootNewPortfolioProjectPage({
  searchParams,
}: RootNewPortfolioProjectPageProps) {
  if (!isAdminAuthenticated()) {
    redirect("/root");
  }

  async function logoutAction() {
    "use server";

    clearAdminSessionCookie();
    redirect("/root");
  }

  const [categories, mediaOptions] = await Promise.all([
    getActivePortfolioCategories(),
    getMediaOptions(),
  ]);

  return (
    <RootDashboardShell
      copy={copy}
      active="portfolio"
      portfolioChild="new-project"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
      saveFormId="portfolio-project-form"
    >
      <div className="space-y-6">
        {searchParams?.error ? (
          <MotionFade delay={0.1}>
            <FlashMessage type="error" message={searchParams.error} />
          </MotionFade>
        ) : null}

        <MotionFade delay={0.15}>
          <PortfolioProjectForm
            action={saveProjectAction}
            categories={categories}
            mediaOptions={mediaOptions}
            formId="portfolio-project-form"
            redirectPath="/root/portfolio/projects/new"
          />
        </MotionFade>
      </div>
    </RootDashboardShell>
  );
}
