import { Suspense } from "react";
import Link from "next/link";
import { Search, Filter } from "lucide-react";
import { catalogApi } from "@/lib/api/catalog";
import type { ApiCategory, ApiProduct, ApiSearchMeta } from "@/lib/api/types";
import ProductCard from "@/components/products/ProductCard";
import { CardGridSkeleton, Skeleton } from "@/components/ui/Skeleton";

export const metadata = {
  title: "Raw Material Products – Biznie",
  description: "Buy raw materials at best prices. Steel, Aluminium, Chemicals, Polymers & more.",
};

export const revalidate = 60;

type PageProps = {
  searchParams: Promise<{ search?: string; category_id?: string }>;
};

async function safeFetchProducts(params: { search?: string; category_id?: number }) {
  try {
    return await catalogApi.products(params, { next: { revalidate: 60 } });
  } catch {
    return { data: [] as ApiProduct[], meta: undefined as { search?: ApiSearchMeta | null } | undefined };
  }
}

async function safeFetchCategories() {
  try {
    const res = await catalogApi.categories({ per_page: 50, with_products: true }, { next: { revalidate: 300 } });
    return res.data;
  } catch {
    return [] as ApiCategory[];
  }
}

/**
 * The page component stays synchronous and passes `searchParams` down as an
 * unawaited promise, so the banner can be streamed before the catalog request
 * resolves. Previously the whole document waited on that fetch.
 *
 * This does NOT make the route static — reading `searchParams` anywhere still
 * marks it dynamic, and `export const revalidate` above stays inert until
 * Partial Prerendering lands in a stable release. The win here is TTFB: the
 * browser gets the shell and starts painting instead of staring at a blank tab
 * for the duration of the upstream call.
 */
export default function ProductsPage({ searchParams }: PageProps) {
  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-gradient-to-r from-[#CC1414] to-[#8B0000] text-white py-14">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <h1 className="text-3xl md:text-4xl font-black mb-3">Raw Material Products</h1>
          <p className="text-red-100 max-w-2xl">
            Buy raw materials at the best prices with verified quality, flexible payment &amp; Pan India delivery.
          </p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <Suspense fallback={<ProductsBodySkeleton />}>
          <ProductsBody searchParams={searchParams} />
        </Suspense>
      </div>
    </div>
  );
}

function ProductsBodySkeleton() {
  return (
    <div className="flex flex-col md:flex-row gap-8">
      <aside className="w-full md:w-56 shrink-0">
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
          <Skeleton className="mb-4 h-4 w-20" />
          <div className="space-y-2">
            {Array.from({ length: 8 }).map((_, i) => (
              <Skeleton key={i} className="h-9 w-full rounded-lg" />
            ))}
          </div>
        </div>
      </aside>
      <div className="flex-1">
        <Skeleton className="mb-6 h-[74px] w-full rounded-2xl" />
        <CardGridSkeleton count={6} />
      </div>
    </div>
  );
}

async function ProductsBody({ searchParams }: PageProps) {
  const sp = await searchParams;
  const search = sp.search?.trim() || undefined;
  const categoryId = sp.category_id ? Number(sp.category_id) : undefined;

  const [productsRes, categories] = await Promise.all([
    safeFetchProducts({ search, category_id: categoryId }),
    safeFetchCategories(),
  ]);
  const products = productsRes.data;
  const understood = productsRes.meta?.search;

  return (
    <div className="flex flex-col md:flex-row gap-8">
      <aside className="w-full md:w-56 shrink-0">
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 md:sticky md:top-24">
          <h3 className="font-bold text-gray-900 text-sm mb-4 flex items-center gap-2">
            <Filter size={15} /> Filters
          </h3>
          <div className="space-y-1">
            <Link
              href="/products"
              className={`block w-full text-left text-sm px-3 py-2 rounded-lg transition-colors ${
                !categoryId ? "bg-[#CC1414] text-white font-semibold" : "text-gray-600 hover:bg-gray-50 hover:text-[#CC1414]"
              }`}
            >
              All Categories
            </Link>
            {categories.map((cat) => (
              <Link
                key={cat.id}
                href={`/products?category_id=${cat.id}`}
                className={`block w-full text-left text-sm px-3 py-2 rounded-lg transition-colors ${
                  categoryId === cat.id
                    ? "bg-[#CC1414] text-white font-semibold"
                    : "text-gray-600 hover:bg-gray-50 hover:text-[#CC1414]"
                }`}
              >
                {cat.name}
              </Link>
            ))}
            {categories.length === 0 && (
              <p className="text-xs text-gray-400">No categories yet.</p>
            )}
          </div>
        </div>
      </aside>

      <div className="flex-1">
        <form action="/products" method="get" className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 mb-6 flex gap-3">
          {categoryId && <input type="hidden" name="category_id" value={categoryId} />}
          <div className="relative flex-1">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              name="search"
              defaultValue={search || ""}
              placeholder="Search products..."
              className="w-full pl-9 pr-4 py-2.5 text-sm text-gray-900 placeholder:text-gray-400 bg-white border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]"
            />
          </div>
          <button type="submit" className="bg-[#CC1414] text-white px-5 py-2.5 rounded-lg text-sm font-semibold hover:bg-[#A50E0E] transition-colors">
            Search
          </button>
        </form>

        {/* "saria 12mm" reads back as "TMT · 12mm", so the buyer sees why these came up. */}
        {search && understood?.synonym_applied && understood.interpreted && products.length > 0 && (
          <p className="mb-4 text-sm text-gray-600">
            Showing results for <span className="font-semibold text-gray-900">{understood.interpreted}</span>
            <span className="text-gray-400"> · you searched “{search}”</span>
          </p>
        )}

        {products.length === 0 ? (
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-12 text-center">
            <p className="text-gray-700 text-sm font-medium">No products found{search ? ` for “${search}”` : ""}.</p>
            {search && (
              <>
                <p className="mt-1 text-sm text-gray-500">Tell us what you need and verified sellers will quote you.</p>
                <div className="mt-5 flex flex-wrap items-center justify-center gap-3">
                  <Link
                    href={`/?product=${encodeURIComponent(search)}#get-quote`}
                    className="rounded-lg bg-[#CC1414] px-5 py-2.5 text-sm font-semibold text-white hover:bg-[#A50E0E]"
                  >
                    Post your requirement
                  </Link>
                  <Link href="/products" className="rounded-lg border border-gray-200 px-5 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50">
                    Browse all products
                  </Link>
                </div>
              </>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {products.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
