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 { getSiteSettings } from "@/lib/app-config";
import { buildLocalizedMetadata } from "@/lib/metadata";
import { FALLBACK_LOCALE, getLocalizedPath, resolveLocale } from "@/lib/locale";
import { getActivePortfolioCategories, getPublishedPortfolioProjects } from "@/lib/portfolio";

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

export const dynamic = "force-dynamic";

export async function generateMetadata({ params }: PortfolioPageProps): Promise<Metadata> {
  const { locale } = await params;
  const localeKey = resolveLocale(locale, FALLBACK_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,
  searchParams,
}: PortfolioPageProps) {
  const [{ locale }, resolvedSearchParams] = await Promise.all([
    params,
    searchParams,
  ]);
  const localeKey = resolveLocale(locale, FALLBACK_LOCALE);
  const [t, siteSettings] = await Promise.all([
    getTranslations({ locale: localeKey, namespace: "portfolioPage" }),
    getSiteSettings(),
  ]);
  const selectedCategory = resolvedSearchParams?.category ?? "";

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

  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}
          defaultLocale={siteSettings.defaultLocale}
          categories={categories}
          allLabel={t("all")}
        />
        <PortfolioProjectGrid
          locale={localeKey}
          defaultLocale={siteSettings.defaultLocale}
          projects={projects}
          emptyLabel={t("empty")}
          openLabel={t("open")}
        />
      </Container>
    </>
  );
}
