import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { notFound } from "next/navigation";

import { Container } from "@/components/layout/container";
import { PageHero } from "@/components/layout/page-hero";
import { PortfolioCategoryFilter } from "@/components/site/portfolio-category-filter";
import { PortfolioProjectGrid } from "@/components/site/portfolio-project-grid";
import { buildLocalizedMetadata } from "@/lib/metadata";
import { resolveLocale } from "@/lib/locale";
import {
  getActivePortfolioCategories,
  getActivePortfolioCategoryBySlug,
  getLocalizedValue,
  getPublishedPortfolioProjects,
} from "@/lib/portfolio";

type PortfolioCategoryPageProps = {
  params: Promise<{
    locale: string;
    slug: string;
  }>;
};

export const dynamic = "force-dynamic";

export async function generateMetadata({ params }: PortfolioCategoryPageProps): Promise<Metadata> {
  const { locale, slug } = await params;
  const localeKey = resolveLocale(locale);
  const t = await getTranslations({ locale: localeKey, namespace: "portfolioPage" });
  const category = await getActivePortfolioCategoryBySlug(slug);

  if (!category) {
    return await buildLocalizedMetadata({
      locale: localeKey,
      pathname: `/portfolio/category/${slug}`,
      title: t("title"),
      description: t("intro"),
    });
  }

  return await buildLocalizedMetadata({
    locale: localeKey,
    pathname: `/portfolio/category/${slug}`,
    title: getLocalizedValue(category.name, localeKey),
    description: getLocalizedValue(category.description, localeKey) || t("intro"),
  });
}

export default async function PortfolioCategoryPage({
  params,
}: PortfolioCategoryPageProps) {
  const { locale, slug } = await params;
  const localeKey = resolveLocale(locale);
  const t = await getTranslations({ locale: localeKey, namespace: "portfolioPage" });
  const [categories, category, projects] = await Promise.all([
    getActivePortfolioCategories(),
    getActivePortfolioCategoryBySlug(slug),
    getPublishedPortfolioProjects({ categorySlug: slug }),
  ]);

  if (!category) {
    notFound();
  }

  return (
    <>
      <PageHero
        locale={localeKey}
        badge={t("heroBadge")}
        title={getLocalizedValue(category.name, localeKey)}
        description={getLocalizedValue(category.description, localeKey) || t("intro")}
      />

      <Container className="flex flex-col gap-section pb-12 lg:pb-16">
        <PortfolioCategoryFilter
          locale={localeKey}
          categories={categories}
          allLabel={t("all")}
          activeCategorySlug={category.slug}
        />
        <PortfolioProjectGrid
          locale={localeKey}
          projects={projects}
          emptyLabel={t("empty")}
          openLabel={t("open")}
        />
      </Container>
    </>
  );
}
