import { Suspense } from "react";
import { notFound } from "next/navigation";
import Banner from "@/components/banner";
import LoadingSpinner from "@/components/loading-spinner";
import ProjectCategoryContent from "./project-category-content";
import { fetchProjectsImage, getProjectCategory } from "@/lib/api";
import Image from "next/image";

interface PageProps {
  params: { category: string };
  searchParams: { page?: string };
}

export default async function Page({ params, searchParams }: PageProps) {
  const page = Number.parseInt(searchParams.page || "1");
  const resp = await fetchProjectsImage();

  try {
    // Fetch the category data
    const categoryResponse = await getProjectCategory(params.category);
    const category = categoryResponse.data;

    console.log(params.category);

    if (category.length === 0) {
      notFound();
    }

    return (
      <>
        {category.image ? (
          <div className="relative h-[400pxo]">
            <div className="absolute inset-0 z-0">
              <Image
                src={category.image || "/placeholder.svg"}
                alt={category.name}
                fill
                className="object-cover"
                priority
              />
              <div className="absolute inset-0 bg-black/60"></div>
            </div>
            <div className="relative z-10 py-32 px-4">
              <div className="max-w-7xl mx-auto text-center text-white">
                <div className="inline-block mb-6 p-2 bg-orange-600/30 backdrop-blur-sm rounded-lg">
                  <Image
                    src={category.image || "/placeholder.svg"}
                    alt={category.name}
                    width={80}
                    height={80}
                    className="w-20 h-20 object-cover rounded-lg"
                  />
                </div>
                <h1 className="text-5xl font-bold mb-4">{category.name}</h1>
                <p className="text-xl text-white/80 max-w-3xl mx-auto">
                  {category.description}
                </p>
              </div>
            </div>
          </div>
        ) : (
          <Banner imageSrc={resp.image_url} height={400}>
            <div className="text-center text-white">
              <h1 className="text-5xl font-bold mb-4">
                {category[0].project_category.name}
              </h1>
              <p className="text-xl text-white/80">{category.description}</p>
            </div>
          </Banner>
        )}

        <Suspense fallback={<LoadingSpinner />}>
          <ProjectCategoryContent
            category={category}
            categoryId={params.category}
            initialPage={page}
            params={params.category}
          />
        </Suspense>
      </>
    );
  } catch (error) {
    console.error("Error loading category:", error);
    notFound();
  }
}
