import { redirect } from "next/navigation";

import { PortfolioCategoriesManager } from "@/components/root/portfolio-categories-manager";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminPortfolioCategories } from "@/lib/portfolio";

import { deleteCategoryAction, upsertCategoryAction } from "../actions";

export const dynamic = "force-dynamic";

const copy = {
  title: "Portfolio Kategorien",
  subtitle: "Kategorien schnell anlegen, oeffnen und direkt im Modal bearbeiten.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "Settings",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
};

export default async function RootPortfolioCategoriesPage() {
  if (!isAdminAuthenticated()) {
    redirect("/root");
  }

  async function logoutAction() {
    "use server";

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

  const categories = await getAdminPortfolioCategories();
  const activeCount = categories.filter((category) => category.isActive).length;
  const assignedProjects = categories.reduce((sum, category) => sum + category.projectCount, 0);

  return (
    <RootDashboardShell
      copy={copy}
      active="portfolio"
      portfolioChild="categories"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
    >
      <div className="space-y-6">
        <PortfolioCategoriesManager
          categories={categories}
          activeCount={activeCount}
          assignedProjects={assignedProjects}
          saveCategoryAction={upsertCategoryAction}
          removeCategoryAction={deleteCategoryAction}
        />
      </div>
    </RootDashboardShell>
  );
}
