import Link from "next/link";
import SafeImage from "@/components/ui/SafeImage";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import ProductCard from "@/components/products/ProductCard";
import { catalogApi } from "@/lib/api/catalog";
import { ApiException } from "@/lib/api/client";
import type { ApiCategory, ApiProduct } from "@/lib/api/types";

type Props = { params: Promise<{ slug: string }> };

export const revalidate = 120;

/**
 * Prebuild the category pages at build time so the first visitor to each one
 * gets a cached document instead of paying for a cold render.
 *
 * Deliberately fail-safe: if the API is unreachable during the build, returning
 * an empty list just means nothing is prerendered. `dynamicParams` defaults to
 * true, so every slug still renders on demand and then caches per `revalidate`.
 */
export async function generateStaticParams(): Promise<{ slug: string }[]> {
  try {
    const res = await catalogApi.categories({ per_page: 100 });
    return res.data
      .map((category) => category.slug)
      .filter((slug): slug is string => Boolean(slug))
      .map((slug) => ({ slug }));
  } catch {
    return [];
  }
}

async function loadCategory(slug: string) {
  try {
    return await catalogApi.category(slug, { next: { revalidate: 300 } });
  } catch (err) {
    if (err instanceof ApiException && err.status === 404) return null;
    throw err;
  }
}

/**
 * By category id (B07). This searched for the category's *name*, so the
 * FINISHED page also listed everything under SEMI FINISHED.
 */
async function safeFetchProducts(categoryId: number) {
  try {
    const res = await catalogApi.products({ category_id: categoryId, per_page: 48 }, { next: { revalidate: 120 } });
    return res.data;
  } catch {
    return [] as ApiProduct[];
  }
}

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const cat = await loadCategory(slug);
  if (!cat) return { title: "Category Not Found – Biznie" };
  return {
    title: cat.meta.title || `${cat.name} – Raw Materials | Biznie`,
    description:
      cat.meta.description || `Browse ${cat.name} products and get live B2B prices on Biznie.`,
  };
}

export default async function CategoryPage({ params }: Props) {
  const { slug } = await params;
  const category = await loadCategory(slug);
  if (!category) notFound();

  const [products, allCategories] = await Promise.all([
    safeFetchProducts(category.id),
    safeFetchAllCategories(),
  ]);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="relative bg-gradient-to-r from-[#CC1414] to-[#8B0000] text-white py-14 overflow-hidden">
        {category.banner && (
          <div className="absolute inset-0 opacity-20">
            <SafeImage
              src={category.banner}
              alt={category.name}
              fill
              sizes="100vw"
              className="object-cover"
            />
          </div>
        )}
        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <p className="text-red-200 text-sm mb-1">
            <Link href="/products" className="hover:text-white">Products</Link> / {category.name}
          </p>
          <h1 className="text-3xl md:text-4xl font-black">{category.name}</h1>
          {category.meta.description && (
            <p className="text-red-100 mt-1 max-w-2xl">{category.meta.description}</p>
          )}
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        {allCategories.length > 0 && (
          <div className="flex gap-2 overflow-x-auto pb-2 mb-8">
            {allCategories.map((c) => (
              <Link
                key={c.id}
                href={`/categories/${c.slug}`}
                className={`shrink-0 text-xs font-semibold px-4 py-2 rounded-full border transition-all ${
                  c.slug === slug
                    ? "bg-[#CC1414] text-white border-[#CC1414]"
                    : "bg-white text-gray-600 border-gray-200 hover:border-[#CC1414] hover:text-[#CC1414]"
                }`}
              >
                {c.name}
              </Link>
            ))}
          </div>
        )}

        {products.length === 0 ? (
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-12 text-center">
            <p className="text-gray-500 text-sm mb-4">
              No products listed under {category.name} yet.
            </p>
            <Link
              href="/contact"
              className="inline-flex items-center gap-2 bg-[#CC1414] text-white text-sm font-semibold px-5 py-2.5 rounded-lg hover:bg-[#A50E0E] transition-colors"
            >
              Submit your requirement →
            </Link>
          </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>
  );
}
