import Container from "@/components/elements/Container";
import { cookies } from "next/headers";
import InfinitePosts from "@/components/academy/InfinitePakage";
import { Metadata } from "next";
import AcademyFilter from "@/components/academy/AcademyFilter";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { getSeoPage } from "@/lib/i18n/seo";
import { generateSeoPageMetadata, getServerLanguage } from "@/lib/i18n/server";
import {
  buildAcademyListSeo,
  AcademyListFilters,
} from "@/lib/buildAcademyListSeo";

interface IAcademyListProps {
  params: Promise<{ slug?: string[] }>;
  searchParams: Promise<{
    search?: string;
    category?: string;
    minPrice?: string;
    maxPrice?: string;
    hasOffer?: string;
    type?: string;
    isFree?: string;
    sortBy?: string;
    sortOrder?: string;
  }>;
};

function normalizeAcademyFilters(
  filters: Awaited<IAcademyListProps["searchParams"]>
): AcademyListFilters {
  let sortBy = filters.sortBy || "createdAt";
  let sortOrder = filters.sortOrder || "desc";

  if (sortBy.includes("_")) {
    const [field, order] = sortBy.split("_");
    sortBy = field;
    sortOrder = order || "desc";
  }

  return {
    search: filters.search || "",
    category: filters.category || "",
    type: filters.type || "",
    isFree: filters.isFree === "true" || filters.type === "free",
    sortBy,
    sortOrder,
  };
}

export async function generateMetadata({
  searchParams,
}: IAcademyListProps): Promise<Metadata> {
  const lang = await getServerLanguage();
  const filters = normalizeAcademyFilters(await searchParams);
  const hasFilters = Boolean(
    filters.category ||
      filters.type ||
      filters.isFree ||
      filters.search ||
      (filters.sortBy && filters.sortBy !== "createdAt")
  );

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

  const seo = buildAcademyListSeo(filters, lang);
  const academyPage = getSeoPage("academy", lang);
  const meta = generatePageMetadata({
    title: seo.title,
    ogTitle: seo.title,
    description: seo.description,
    path: seo.path,
    keywords: academyPage.keywords,
    lang,
  });

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

export default async function AcademyListPage({
  searchParams,
}: IAcademyListProps) {
  const params = await searchParams;
  const cookieStore = await cookies();
  const token = cookieStore.get("token")?.value || "";
  const seo = buildAcademyListSeo(normalizeAcademyFilters(params));

  const filters = {
    search: params.search || "",
    category: params.category || "",
    minPrice: params.minPrice ? Number(params.minPrice) : undefined,
    maxPrice: params.maxPrice ? Number(params.maxPrice) : undefined,
    hasOffer: params.hasOffer === "true",
    type: params.type === "free" ? "" : params.type || "",
    isFree: params.isFree === "true" || params.type === "free",
    ...(() => {
      let sortBy = params.sortBy || "createdAt";
      let sortOrder = params.sortOrder || "desc";
      if (sortBy.includes("_")) {
        const [field, order] = sortBy.split("_");
        sortBy = field;
        sortOrder = order || "desc";
      }
      return { sortBy, sortOrder };
    })(),
  };

  return (
    <Container>
      <h1 className="sr-only">{seo.h1}</h1>
      <AcademyFilter />
      <InfinitePosts filters={filters} token={token} />
    </Container>
  );
}
