import { redirect } from "next/navigation";

import { PortfolioCategoriesManager } from "@/components/admin/portfolio-categories-manager";
import { AdminDashboardShell } from "@/components/admin/admin-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminAppPath } from "@/lib/admin-routing";
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 AdminPortfolioCategoriesPage() {
  if (!(await isAdminAuthenticated())) {
    redirect(getAdminAppPath("/"));
  }

  async function logoutAction() {
    "use server";

    await clearAdminSessionCookie();
    redirect(getAdminAppPath("/"));
  }

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

  return (
    <AdminDashboardShell
      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>
    </AdminDashboardShell>
  );
}
