import { Metadata } from "next";
import { Suspense } from "react";
import { cookies } from "next/headers";
import ProjectDetailClient from "./ProjectDetailClient";
import PageLoader from "@/components/ui/PageLoader";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { fetchProject } from "@/api/fetchProject";
import {
  buildProjectDetailFallbackSeo,
  buildProjectDetailSeo,
} from "@/lib/buildProjectDetailSeo";
import { getServerLanguage } from "@/lib/i18n/server";

type ProjectDetailPageProps = {
  params: Promise<{ id: string; title: string }>;
};

export async function generateMetadata({
  params,
}: ProjectDetailPageProps): Promise<Metadata> {
  const { id, title } = await params;
  const token = (await cookies()).get("token")?.value || "";
  const lang = await getServerLanguage();
  const project = await fetchProject(id, token);

  if (project) {
    const seo = buildProjectDetailSeo(project, lang);
    return generatePageMetadata({
      title: seo.title,
      description: seo.description,
      path: seo.path,
      type: "article",
      lang,
    });
  }

  const seo = buildProjectDetailFallbackSeo(
    decodeURIComponent(title || ""),
    id,
    lang
  );
  return generatePageMetadata({
    title: seo.title,
    description: seo.description,
    path: seo.path,
    lang,
  });
}

export default async function ProjectDetailPage({
  params,
}: ProjectDetailPageProps) {
  const { id } = await params;

  return (
    <Suspense fallback={<PageLoader className="min-h-[50vh]" />}>
      <ProjectDetailClient id={id} />
    </Suspense>
  );
}
