import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { redirect } 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 { getLocalizedPath, resolveLocale } from "@/lib/locale";
import { getActivePortfolioCategories, getPublishedPortfolioProjects } from "@/lib/portfolio";

type PortfolioPageProps = {
  params: {
    locale: string;
  };
  searchParams?: {
    category?: string;
  };
};

export const dynamic = "force-dynamic";

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

  return await buildLocalizedMetadata({
    locale: localeKey,
    pathname: "/portfolio",
    title: t("title"),
    description: t("intro"),
  });
}

export default async function PortfolioPage({
  params: { locale },
  searchParams,
}: PortfolioPageProps) {
  const localeKey = resolveLocale(locale);
  const t = await getTranslations({ locale: localeKey, namespace: "portfolioPage" });
  const selectedCategory = searchParams?.category ?? "";

  if (selectedCategory) {
    redirect(getLocalizedPath(localeKey, `/portfolio/category/${selectedCategory}`));
  }

  const [categories, projects] = await Promise.all([
    getActivePortfolioCategories(),
    getPublishedPortfolioProjects(),
  ]);

  return (
    <>
      <PageHero
        locale={localeKey}
        badge={t("heroBadge")}
        title={t("heroTitle")}
        description={t("intro")}
      />

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