"use client";

import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Container } from "@/components/ui/container";
import { TypographyH3 } from "@/components/ui/typography";
import ProductCard from "./ProductCard";
import { useProducts } from "@/hooks/useProducts";
import { convertApiProductToProduct } from "@/types/api";
import { OptimizedLazyLoad, LazyLoadSkeleton } from "@/components/ui/optimized-lazy-load";
import type { Product } from "@/types/product";

interface ProductsGridProps {
  title?: string;
  subtitle?: string;
  categoryId?: number;
  limit?: number;
  showViewAll?: boolean;
  className?: string;
  enableCache?: boolean;
  priority?: boolean; // For above-the-fold content
  sortBy?: 'created_at' | 'name' | 'base_price' | 'updated_at';
  sortOrder?: 'asc' | 'desc';
}

// Skeleton component for loading state
const ProductGridSkeleton = () => (
  <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-6">
    {Array.from({ length: 8 }).map((_, index) => (
      <LazyLoadSkeleton key={index} height="400px" className="rounded-lg" />
    ))}
  </div>
);

const ProductsGrid: React.FC<ProductsGridProps> = ({
  title = "Latest Products",
  subtitle,
  categoryId,
  limit = 8,
  showViewAll = true,
  className = "",
  enableCache = true,
  priority = false,
  sortBy = 'created_at',
  sortOrder = 'desc'
}) => {
  const [favorites, setFavorites] = useState<Record<string, boolean>>({});
  const [mounted, setMounted] = useState(false);
  
  const { 
    products: apiProducts, 
    loading, 
    error, 
    fromCache,
    prefetch 
  } = useProducts({
    category_id: categoryId,
    sort_by: sortBy,
    sort_order: sortOrder,
    enableCache,
    autoFetch: priority, // Only auto-fetch if priority content
  });

  // Memoize converted products to prevent unnecessary recalculations
  const products = useMemo(() => 
    apiProducts.slice(0, limit).map(convertApiProductToProduct),
    [apiProducts, limit]
  );

  // Optimized toggle favorite function
  const toggleFav = useCallback((id: string) => {
    setFavorites((prev) => {
      const updated = { ...prev, [id]: !prev[id] };
      // Batch localStorage updates
      requestIdleCallback(() => {
        try {
          localStorage.setItem("product_favorites", JSON.stringify(updated));
        } catch (error) {
          console.warn('Failed to save favorites:', error);
        }
      });
      return updated;
    });
  }, []);

  // Load favorites from localStorage on mount
  useEffect(() => {
    setMounted(true);
    try {
      const raw = localStorage.getItem("product_favorites");
      if (raw) {
        setFavorites(JSON.parse(raw));
      }
    } catch (error) {
      console.warn('Failed to load favorites:', error);
    }
  }, []);

  // Prefetch related data when component becomes visible
  const handleVisible = useCallback(() => {
    if (!priority) {
      // Prefetch next category or page
      if (categoryId) {
        prefetch({ category_id: categoryId + 1 });
      } else {
        prefetch({ page: 2 });
      }
    }
  }, [priority, categoryId, prefetch]);

  // Don't render until mounted to prevent hydration issues
  if (!mounted) {
    return (
      <section className={`py-12 px-4 md:px-6 ${className}`}>
        <Container>
          <ProductGridSkeleton />
        </Container>
      </section>
    );
  }

  if (error) {
    return (
      <section className={`py-12 px-4 md:px-6 ${className}`}>
        <Container>
          <div className="text-center">
            <p className="text-red-500">Error loading products: {error}</p>
            <button 
              onClick={() => window.location.reload()}
              className="mt-2 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              Retry
            </button>
          </div>
        </Container>
      </section>
    );
  }

  const content = (
    <section className={`py-12 px-4 md:px-6 ${className}`}>
      <Container>
        <div className="flex items-center justify-between mb-8">
          <div>
            <TypographyH3 className="text-[36px] sm:text-[47px] leading-10 sm:leading-[59px] font-bold prompt tracking-[-0.94px] text-black">
              {title}
              {fromCache && (
                <span className="ml-2 text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full">
                  Cached
                </span>
              )}
            </TypographyH3>
            {subtitle && (
              <p className="text-gray-600 mt-2">{subtitle}</p>
            )}
          </div>
          
          {showViewAll && (
            <a 
              href={categoryId ? `/products?category=${categoryId}` : '/products'}
              className="text-[#F5411C] hover:text-[#e63914] font-medium transition-colors duration-200"
            >
              View All →
            </a>
          )}
        </div>

        {loading && products.length === 0 ? (
          <ProductGridSkeleton />
        ) : products.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-gray-500">No products found.</p>
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {products.map((product: Product, index) => (
              <div key={product.id} className="h-full">
                {/* Lazy load non-priority items */}
                {!priority && index > 3 ? (
                  <OptimizedLazyLoad
                    fallback={<LazyLoadSkeleton height="400px" className="rounded-lg" />}
                    onVisible={index === 4 ? handleVisible : undefined}
                    delay={index * 100} // Stagger loading
                  >
                    <ProductCard
                      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)}
                    />
                  </OptimizedLazyLoad>
                ) : (
                  <ProductCard
                    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>
            ))}
          </div>
        )}
      </Container>
    </section>
  );

  // Wrap non-priority content in lazy loading
  if (!priority) {
    return (
      <OptimizedLazyLoad
        fallback={
          <section className={`py-12 px-4 md:px-6 ${className}`}>
            <Container>
              <ProductGridSkeleton />
            </Container>
          </section>
        }
        onVisible={handleVisible}
      >
        {content}
      </OptimizedLazyLoad>
    );
  }

  return content;
};

export default React.memo(ProductsGrid);