import React, { Suspense } from 'react';
import Link from 'next/link';
import ProductListWithFilters from '../../../components/ProductListWithFilters';
import { generateSlug } from '../../../../utils/slugHelper';
import { notFound } from 'next/navigation';

type Product = {
  inward_id: string;
  variant_id: string;
  sku_no: string;
  name: string;
  image: string | null;
  dealer_price: number;
  mrp: number;
  color: string;
  size_name: string;
  is_individual: boolean;
  is_carton: boolean;
  is_featured: boolean;
  is_new_arrival: boolean;
  is_best_seller: boolean;
  is_active: boolean;
  category_id: string | null;
  category_name: string | null;
  subcategory_id: string | null;
  subcategory_name: string | null;
};

type Category = {
  name: string;
  is_active: boolean;
  category_id: string;
};

type Subcategory = {
  name: string;
  category_id: string;
  subcategory_id: string;
};

async function getCategories() {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/product-master/categories/`,
      { cache: 'no-store' }
    );
    if (!res.ok) return [];
    return (await res.json()) as Category[];
  } catch (error) {
    console.error("Error fetching categories:", error);
    return [];
  }
}

async function getSubcategories() {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/product-master/subcategories/`,
      { cache: 'no-store' }
    );
    if (!res.ok) return [];
    return (await res.json()) as Subcategory[];
  } catch (error) {
    console.error("Error fetching subcategories:", error);
    return [];
  }
}

async function getCategoryProducts(categoryId: string, subcategoryId: string) {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-admin/inwards/cards?category_id=${categoryId}&subcategory_id=${subcategoryId}&is_active=true`,
      { cache: 'no-store' }
    );
    if (!res.ok) return [];
    return (await res.json()) as Product[];
  } catch (error) {
    console.error("Error fetching filtered category products:", error);
    return [];
  }
}

export default async function SubcategoryPage({
  params,
}: {
  params: Promise<{ category_slug: string; subcategory_slug: string }>;
}) {
  const resolvedParams = await params;
  const { category_slug, subcategory_slug } = resolvedParams;

  // 1. Resolve category slug to ID
  const categories = await getCategories();
  const category = categories.find(c => generateSlug(c.name) === category_slug);

  if (!category) {
    notFound();
  }

  // 2. Resolve subcategory slug to ID
  const allSubcategories = await getSubcategories();
  // Ensure the subcategory belongs to the matched category
  const categorySubcategories = allSubcategories.filter(s => s.category_id === category.category_id);
  const subcategory = categorySubcategories.find(s => generateSlug(s.name) === subcategory_slug);

  if (!subcategory) {
    notFound();
  }

  // 3. Fetch products filtered by both IDs
  const filteredProducts = await getCategoryProducts(category.category_id, subcategory.subcategory_id);

  // Format all subcategories for the tabs
  const subcategoriesForTabs = categorySubcategories.map(s => ({
    id: s.subcategory_id,
    name: s.name,
    slug: generateSlug(s.name)
  }));

  return (
    <div className="min-h-screen bg-transparent">
      <div className="max-w-[90rem] mx-auto px-4 sm:px-6 lg:px-8 pt-28 pb-20">

      <Suspense fallback={
        <div className="flex justify-center items-center py-20">
          <span className="w-10 h-10 border-4 border-primary/30 border-t-primary rounded-full animate-spin"></span>
        </div>
      }>
        <ProductListWithFilters initialProducts={filteredProducts} />
      </Suspense>
      </div>
    </div>
  );
}
