"use client";

import React, { Suspense } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { Container } from "@/components/ui/container";
import { TypographyH3 } from "@/components/ui/typography";
import ProductCard from "@/components/ProductCard";
import { Pagination } from "@/components/ui/pagination";
import { ProductsGridSkeleton } from "@/components/ui/skeleton";
import { useProducts } from "@/hooks/useProducts";
import { useCategories } from "@/hooks/useCategories";
import { convertApiProductToProduct } from "@/types/api";
import type { Product } from "@/types/product";

// Disable static generation for this page
export const dynamic = 'force-dynamic';

function ProductsPageContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  
  const categoryId = searchParams?.get('category') ? Number(searchParams.get('category')) : undefined;
  const search = searchParams?.get('search') || undefined;
  const currentPage = searchParams?.get('page') ? Number(searchParams.get('page')) : 1;

  const [favorites, setFavorites] = React.useState<Record<string, boolean>>({});
  
  const { products: apiProducts, loading, error, pagination } = useProducts({
    category_id: categoryId,
    search: search,
    page: currentPage,
  });

  const { categories } = useCategories();

  // Convert API products to frontend format
  const products = React.useMemo(() => 
    apiProducts.map(convertApiProductToProduct),
    [apiProducts]
  );

  // Find current category name
  const currentCategory = React.useMemo(() => {
    if (!categoryId) return null;
    return categories.find(cat => cat.id === categoryId) || 
           categories.flatMap(cat => cat.children || []).find(cat => cat.id === categoryId);
  }, [categoryId, categories]);

  const toggleFav = (id: string) =>
    setFavorites((prev) => ({ ...prev, [id]: !prev[id] }));

  // Handle page change
  const handlePageChange = (page: number) => {
    const params = new URLSearchParams(searchParams?.toString());
    params.set('page', page.toString());
    router.push(`${pathname}?${params.toString()}`);
    
    // Scroll to top of the page smoothly
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // Load favorites from localStorage
  React.useEffect(() => {
    try {
      const raw = localStorage.getItem("product_favorites");
      if (raw) setFavorites(JSON.parse(raw));
    } catch { }
  }, []);

  // Save favorites to localStorage
  React.useEffect(() => {
    try {
      localStorage.setItem("product_favorites", JSON.stringify(favorites));
    } catch { }
  }, [favorites]);

  const getPageTitle = () => {
    if (search) return `Search results for "${search}"`;
    if (currentCategory) return currentCategory.name;
    return "كل المنتجات";
  };

  const getSubtitle = () => {
    if (search) return `Found ${products.length} products`;
    if (currentCategory) return currentCategory.description || `Shop ${currentCategory.name}`;
    return "اكتشف مجموعتنا الكاملة من المنتجات";
  };

  return (
    <div className="min-h-screen py-8 px-2">
      <Container>
        {/* Header */}
        <div className="mb-8">
          <TypographyH3 className="text-[36px] sm:text-[47px] leading-10 sm:leading-[59px] font-bold prompt tracking-[-0.94px] text-black">
            {getPageTitle()}
          </TypographyH3>
          <p className="text-gray-600 mt-2">{getSubtitle()}</p>
        </div>

        {/* Loading State */}
        {loading && (
          <ProductsGridSkeleton count={8} />
        )}

        {/* Error State */}
        {error && (
          <div className="text-center py-12">
            <p className="text-red-500">Error loading products: {error}</p>
          </div>
        )}

        {/* No Products */}
        {!loading && !error && products.length === 0 && (
          <div className="text-center py-12">
            <p className="text-gray-500 text-lg">No products found.</p>
            {search && (
              <p className="text-gray-400 mt-2">Try adjusting your search terms.</p>
            )}
          </div>
        )}

        {/* Products Grid */}
        {!loading && !error && products.length > 0 && (
          <>
            <div className={`grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-6 ${loading ? 'opacity-50 pointer-events-none' : ''}`}>
              {products.map((product: Product) => (
                <ProductCard
                  key={product.id}
                  id={product.id}
                  slug={product.slug}
                  title={product.title}
                  price={product.price}
                  imageSrc={product.imageSrc}
                  rating={product.rating || 4.5}
                  ratingCount={product.ratingCount || 100}
                  variant="featured"
                  isFavorite={!!favorites[product.id]}
                  onToggleFavorite={() => toggleFav(product.id)}
                />
              ))}
            </div>

            {/* Pagination */}
            {pagination && (
              <Pagination
                currentPage={pagination.current_page}
                lastPage={pagination.last_page}
                total={pagination.total}
                from={pagination.from}
                to={pagination.to}
                onPageChange={handlePageChange}
                loading={loading}
              />
            )}
          </>
        )}
      </Container>
    </div>
  );
}

export default function ProductsPage() {
  return (
    <Suspense fallback={<ProductsGridSkeleton />}>
      <ProductsPageContent />
    </Suspense>
  );
}