import Container from "@/components/elements/Container";
import InfiniteProjects from "@/components/projects/InfiniteProjects";
import ProjectsFilter from "@/components/projects/ProjectsFilter";
import { fetchProjects } from "@/api/fetchProjects";
import { cookies } from "next/headers";
import { Metadata } from "next";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { getSeoPage } from "@/lib/i18n/seo";
import { generateSeoPageMetadata, getServerLanguage } from "@/lib/i18n/server";
import {
  buildProjectsListSeo,
  ProjectListFilters,
} from "@/lib/buildProjectsListSeo";

type ProjectsPageProps = {
  searchParams: Promise<{
    expertise?: string;
    most_requests?: string;
    most_price?: string;
    age?: string;
    gender?: string;
  }>;
};

function normalizeProjectFilters(
  filters: Awaited<ProjectsPageProps["searchParams"]>
): ProjectListFilters {
  return {
    expertise: filters.expertise || "",
    most_requests: filters.most_requests || "",
    most_price: filters.most_price || "",
    age: filters.age || "",
    gender: filters.gender || "",
  };
}

export async function generateMetadata({
  searchParams,
}: ProjectsPageProps): Promise<Metadata> {
  const lang = await getServerLanguage();
  const filters = normalizeProjectFilters(await searchParams);
  const hasFilters = Object.values(filters).some(Boolean);

  if (!hasFilters) {
    return generateSeoPageMetadata("projects", { lang });
  }

  const seo = buildProjectsListSeo(filters, lang);
  const projectsPage = getSeoPage("projects", lang);

  const meta = generatePageMetadata({
    title: seo.title,
    ogTitle: seo.title,
    description: seo.description,
    path: seo.path,
    keywords: projectsPage.keywords,
    lang,
  });

  return {
    ...meta,
    title: { absolute: seo.title },
  };
}

export default async function ProjectsPage({ searchParams }: ProjectsPageProps) {
  const rawFilters = await searchParams;
  const projectFilters = normalizeProjectFilters(rawFilters);
  const seo = buildProjectsListSeo(projectFilters);
  const cookieStore = await cookies();
  const token = cookieStore.get("token")?.value || "";

  const initialData = await fetchProjects(1, 10, projectFilters, token);

  return (
    <Container className="pb-28">
      <h1 className="sr-only">{seo.h1}</h1>
      <ProjectsFilter expertise={rawFilters.expertise || ""} />
      <InfiniteProjects
        initialData={initialData}
        filters={projectFilters}
        token={token}
      />
    </Container>
  );
}
