import { redirect } from "next/navigation";

import { MotionFade } from "@/components/motion-fade";
import { PortfolioProjectForm } from "@/components/root/portfolio-project-form";
import { PortfolioSubnav } from "@/components/root/portfolio-subnav";
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",
  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}
      toolbar={<PortfolioSubnav active="projects" />}
    >
      <div className="space-y-6">
        {searchParams?.error ? (
          <MotionFade delay={0.1}>
            <p className="rounded-nested border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
              {searchParams.error}
            </p>
          </MotionFade>
        ) : null}

        <MotionFade delay={0.15}>
          <PortfolioProjectForm
            action={saveProjectAction}
            categories={categories}
            mediaOptions={mediaOptions}
            redirectPath="/root/portfolio/projects/new"
            submitLabel="Projekt anlegen"
          />
        </MotionFade>
      </div>
    </RootDashboardShell>
  );
}
