import React, { useEffect, useState, useMemo } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import { useProductStore } from '@/store/productStore';
import { useCategoryStore } from '@/store/categoryStore';
import ProductCard from '@/components/ProductCard';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { Search, Filter, PackageX } from 'lucide-react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { trackPageView } from '@/lib/facebookPixel';

const ProductsPage = () => {
  const { products, fetchProducts, isLoading } = useProductStore();
  const { categories, fetchCategories } = useCategoryStore();
  
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');

  useEffect(() => {
    trackPageView();
    fetchProducts({ itemsPerPage: 50 }); 
    fetchCategories();
  }, []);

  // Performance Optimization: Memoize filtering logic
  const filteredProducts = useMemo(() => {
    return products.filter(product => {
        const matchesSearch = product.name.toLowerCase().includes(searchQuery.toLowerCase());
        const matchesCategory = selectedCategory === 'all' || product.category_id === selectedCategory;
        return matchesSearch && matchesCategory;
    });
  }, [products, searchQuery, selectedCategory]);

  return (
    <>
      <Helmet>
        <title>পণ্য সমূহ | মিনি মার্ভেলস</title>
        <meta name="description" content="আমাদের সকল খেলনা এবং শিক্ষামূলক পণ্যের সংগ্রহ।" />
      </Helmet>

      <div className="bg-slate-50 min-h-screen py-10">
        <div className="container mx-auto px-4">
          
          {/* Header */}
          <div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
            <div>
               <h1 className="text-3xl font-bold text-slate-800">আমাদের পণ্যসমূহ</h1>
               <p className="text-slate-500 mt-1">সেরা মানের খেলনা এবং শিক্ষামূলক সামগ্রী</p>
            </div>
            
            <div className="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
               <div className="relative w-full sm:w-64">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                  <Input 
                    placeholder="পণ্য খুঁজুন..." 
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-9 bg-white"
                  />
               </div>
               
               <div className="w-full sm:w-48">
                  <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                    <SelectTrigger className="bg-white">
                       <Filter className="w-4 h-4 mr-2 text-slate-500" />
                       <SelectValue placeholder="ক্যাটাগরি" />
                    </SelectTrigger>
                    <SelectContent>
                       <SelectItem value="all">সব ক্যাটাগরি</SelectItem>
                       {categories.map(cat => (
                          <SelectItem key={cat.id} value={cat.id}>{cat.name}</SelectItem>
                       ))}
                    </SelectContent>
                  </Select>
               </div>
            </div>
          </div>

          {/* Product Grid */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {isLoading ? (
               // Loading Skeletons
               Array.from({ length: 8 }).map((_, i) => (
                 <div key={i} className="bg-white rounded-2xl border p-4 space-y-4">
                    <Skeleton className="h-64 w-full rounded-xl" />
                    <div className="space-y-2">
                       <Skeleton className="h-4 w-1/3" />
                       <Skeleton className="h-6 w-2/3" />
                       <Skeleton className="h-4 w-1/4" />
                    </div>
                    <Skeleton className="h-10 w-full rounded-lg" />
                 </div>
               ))
            ) : filteredProducts.length > 0 ? (
               filteredProducts.map((product) => (
                  <ProductCard key={product.id} product={product} />
               ))
            ) : (
               // Empty State
               <div className="col-span-full py-20 flex flex-col items-center justify-center text-center">
                  <div className="w-20 h-20 bg-slate-200 rounded-full flex items-center justify-center mb-4">
                     <PackageX className="w-10 h-10 text-slate-400" />
                  </div>
                  <h3 className="text-xl font-bold text-slate-700 mb-2">কোন পণ্য পাওয়া যায়নি</h3>
                  <p className="text-slate-500 max-w-sm mx-auto">
                     আপনার অনুসন্ধানের সাথে মেলে এমন কোনো পণ্য নেই। অনুগ্রহ করে অন্য কীওয়ার্ড দিয়ে চেষ্টা করুন বা ক্যাটাগরি পরিবর্তন করুন।
                  </p>
                  <Button 
                    variant="outline" 
                    className="mt-6"
                    onClick={() => { setSearchQuery(''); setSelectedCategory('all'); }}
                  >
                     ফিল্টার রিসেট করুন
                  </Button>
               </div>
            )}
          </div>

        </div>
      </div>
    </>
  );
};

export default ProductsPage;