import { Suspense } from "react";
import CategoryClient from "./CategoryClient";
import { serverApiClient } from "@/utils/serverApiClient";
import type { Metadata } from "next";
import BreadcrumbList from "../components/common/BreadcrumbList";

// Enable ISR - revalidate every hour
export const revalidate = 3600;

// Optimize for edge runtime (optional - faster, lower cost)
export const runtime = "edge";

export async function generateMetadata({
  searchParams,
}: {
  searchParams: Promise<Record<string, string>>;
}): Promise<Metadata> {
  const params = await searchParams;

  const category = params.category;

  return {
    title: category
      ? `${category} Clothing Collection | Morni`
      : "Shop Sustainable Clothing Collections | Morni",

    description: category
      ? `Explore ${category} clothing crafted from natural fabrics and traditional Indian craftsmanship.`
      : "Browse sustainable clothing collections by category, fabric, design house and style.",
  };
}

export default async function CategoryPage({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  // Await searchParams in Next.js 15+
  const params = await searchParams;

  // Build query parameters for product filtering on server
  const productQueryParams: Record<string, any> = {};

  if (params.vibe) productQueryParams.hasVibeFilter = params.vibe;
  if (params.category) productQueryParams.hasCategoryFilter = params.category;
  if (params.fabric) productQueryParams.hasFabricFilter = params.fabric;
  if (params.color) productQueryParams.hasColorFilter = params.color;
  if (params.design_house)
    productQueryParams.hasDesignHouseFilter = params.design_house;
  if (params.tags) productQueryParams.hasTagFilter = params.tags;
  if (params.size) productQueryParams.hasSizeFilter = params.size;
  if (params.creator) productQueryParams.creatorSlug = params.creator;
  if (params.CoCreator) productQueryParams.coCreatorSlug = params.CoCreator;
  if (params.Gender) productQueryParams.genderSlug = params.Gender;
  if (params.sort) productQueryParams.sorting = params.sort;

  // Check if any filters are applied
  const hasFilters = Object.keys(productQueryParams).length > 0;

  console.log("[Category] products2 query", {
    hasFilters,
    query: productQueryParams,
  });

  // Fetch filter data on server with caching
  const [filterRes, productsRes] = await Promise.all([
    serverApiClient("filter", { revalidate: 3600 }), // Cache for 1 hour
    // Fetch products - no cache when filters applied, cache otherwise
    serverApiClient("products2", {
      cache: hasFilters ? "no-store" : "force-cache",
      revalidate: hasFilters ? false : 600,
      query: productQueryParams,
    }),
  ]);

  const filterData = filterRes.data?.filter_option || [];
  const products = productsRes.data?.product || [];
  const pagination = productsRes.data?.pagination || null;

  // Create a key based on filters to force re-render when filters change
  const filterKey = JSON.stringify(productQueryParams);

  return (
    <>
      <BreadcrumbList
        items={[
          {
            name: "Home",
            url: "https://mymorni.com",
          },
          {
            name: "Category",
            url: "https://mymorni.com/category",
          },
        ]}
      />

      <Suspense
        key={filterKey}
        fallback={
          <div className="flex min-h-[60vh] w-full flex-col items-center justify-center">
            <div className="relative">
              <div className="h-16 w-16 animate-spin rounded-full border-4 border-gray-200 border-t-black"></div>
              <div className="absolute top-1/2 left-1/2 h-2 w-2 -translate-x-1/2 -translate-y-1/2 animate-pulse rounded-full bg-black"></div>
            </div>
            <div className="mt-6 text-center">
              <h3 className="mb-2 text-lg font-medium text-gray-900">
                Loading Products
              </h3>
              <p className="text-sm text-gray-500">
                Please wait while we fetch the latest products for you...
              </p>
            </div>
          </div>
        }
      >
        <CategoryClient
          key={filterKey}
          filterData={filterData}
          products={products}
          pagination={pagination}
          initialQueryParams={productQueryParams}
        />
      </Suspense>
      <div className="wrapper">
        <div className="flex flex-col gap-1 py-8">
          <h1>
            Shop Sustainable Clothing Collections
          </h1>
          <h2>
            Explore handcrafted garments, natural fabrics, and custom-made
            clothing designed by independent creators.
          </h2>
        </div>
      </div>
    </>
  );
}
