'use client';

import { useState, useMemo } from 'react';
import Link from 'next/link';
import ProductCard from '@/components/product/ProductCard';
import type { Product, Category } from '@/lib/types';

interface Props {
  products: Product[];
  categories: Category[];
  initialParams: Record<string, string>;
}

export default function CategoryClient({ products, categories, initialParams }: Props) {
  const [selectedCategory, setSelectedCategory] = useState(initialParams.cat || '');
  const [sortBy, setSortBy] = useState(initialParams.sort || 'featured');
  const [priceRange, setPriceRange] = useState<[number, number]>([0, 5000]);
  const [searchQuery] = useState(initialParams.q || '');
  const [showAuctions, setShowAuctions] = useState(initialParams.auction === 'true');
  const [selectedBrand, setSelectedBrand] = useState(initialParams.brand || '');

  const brands = useMemo(() => {
    const b = new Set(products.map(p => p.brand).filter(Boolean));
    return Array.from(b).sort();
  }, [products]);

  const filtered = useMemo(() => {
    let result = [...products];

    if (selectedCategory) {
      result = result.filter(p => p.category?.slug === selectedCategory);
    }
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      result = result.filter(p => p.name.toLowerCase().includes(q) || p.brand?.toLowerCase().includes(q) || p.description?.toLowerCase().includes(q));
    }
    if (showAuctions) {
      result = result.filter(p => p.is_auction);
    }
    if (selectedBrand) {
      result = result.filter(p => p.brand === selectedBrand);
    }
    result = result.filter(p => p.price >= priceRange[0] && p.price <= priceRange[1]);

    switch (sortBy) {
      case 'price-low': result.sort((a, b) => a.price - b.price); break;
      case 'price-high': result.sort((a, b) => b.price - a.price); break;
      case 'rating': result.sort((a, b) => b.rating - a.rating); break;
      case 'reviews': result.sort((a, b) => b.reviews_count - a.reviews_count); break;
      case 'newest': result.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); break;
    }

    return result;
  }, [products, selectedCategory, sortBy, priceRange, searchQuery, showAuctions, selectedBrand]);

  return (
    <div className="max-w-7xl mx-auto px-4 py-6">
      {/* Breadcrumb */}
      <nav className="flex items-center gap-2 text-sm text-gray-500 mb-4">
        <Link href="/" className="hover:text-primary">Home</Link>
        <span>/</span>
        <span className="text-gray-800 font-semibold">{selectedCategory ? categories.find(c => c.slug === selectedCategory)?.name || 'Category' : 'All Products'}</span>
      </nav>

      <div className="flex gap-6">
        {/* Sidebar Filters */}
        <aside className="hidden md:block w-60 shrink-0 space-y-6">
          {/* Categories */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4">
            <h3 className="font-bold text-sm text-gray-800 mb-3">Categories</h3>
            <div className="space-y-1">
              <button onClick={() => setSelectedCategory('')} className={`w-full text-left px-3 py-2 rounded-lg text-sm ${!selectedCategory ? 'bg-blue-50 text-primary font-semibold' : 'text-gray-600 hover:bg-gray-50'}`}>
                All Categories
              </button>
              {categories.map(cat => (
                <button key={cat.id} onClick={() => setSelectedCategory(cat.slug)} className={`w-full text-left px-3 py-2 rounded-lg text-sm flex items-center gap-2 ${selectedCategory === cat.slug ? 'bg-blue-50 text-primary font-semibold' : 'text-gray-600 hover:bg-gray-50'}`}>
                  <span>{cat.icon}</span> {cat.name}
                </button>
              ))}
            </div>
          </div>

          {/* Price Range */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4">
            <h3 className="font-bold text-sm text-gray-800 mb-3">Price Range</h3>
            <input type="range" min="0" max="5000" step="50" value={priceRange[1]} onChange={e => setPriceRange([0, parseInt(e.target.value)])} className="w-full" />
            <div className="flex justify-between text-xs text-gray-500 mt-1">
              <span>$0</span><span>${priceRange[1].toLocaleString()}</span>
            </div>
          </div>

          {/* Brands */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4">
            <h3 className="font-bold text-sm text-gray-800 mb-3">Brands</h3>
            <div className="space-y-1">
              <button onClick={() => setSelectedBrand('')} className={`w-full text-left px-3 py-1.5 rounded-lg text-sm ${!selectedBrand ? 'text-primary font-semibold' : 'text-gray-600 hover:bg-gray-50'}`}>
                All Brands
              </button>
              {brands.map(b => (
                <button key={b} onClick={() => setSelectedBrand(b)} className={`w-full text-left px-3 py-1.5 rounded-lg text-sm ${selectedBrand === b ? 'text-primary font-semibold' : 'text-gray-600 hover:bg-gray-50'}`}>
                  {b}
                </button>
              ))}
            </div>
          </div>

          {/* Auction Filter */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4">
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" checked={showAuctions} onChange={e => setShowAuctions(e.target.checked)} className="w-4 h-4 rounded" />
              <span className="text-sm font-semibold text-gray-800">🔥 Live Auctions Only</span>
            </label>
          </div>
        </aside>

        {/* Main Content */}
        <div className="flex-1">
          {/* Sort / Count Bar */}
          <div className="flex items-center justify-between mb-4 bg-white rounded-xl p-3 shadow-sm border border-gray-100">
            <p className="text-sm text-gray-600">{filtered.length} product{filtered.length !== 1 ? 's' : ''} found</p>
            <select value={sortBy} onChange={e => setSortBy(e.target.value)} className="text-sm border border-gray-200 rounded-lg px-3 py-2">
              <option value="featured">Featured</option>
              <option value="price-low">Price: Low to High</option>
              <option value="price-high">Price: High to Low</option>
              <option value="rating">Highest Rated</option>
              <option value="reviews">Most Reviewed</option>
              <option value="newest">Newest</option>
            </select>
          </div>

          {/* Product Grid */}
          {filtered.length > 0 ? (
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-3 gap-4">
              {filtered.map(p => <ProductCard key={p.id} product={p} />)}
            </div>
          ) : (
            <div className="text-center py-20">
              <div className="text-6xl mb-4">🔍</div>
              <h3 className="text-xl font-bold text-gray-800 mb-2">No products found</h3>
              <p className="text-gray-500 mb-4">Try adjusting your filters or search terms</p>
              <button onClick={() => { setSelectedCategory(''); setSelectedBrand(''); setPriceRange([0, 5000]); setShowAuctions(false); }}
                className="btn-primary px-6 py-2.5 rounded-xl text-sm font-semibold">Clear All Filters</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
