'use client';

import { useState, useMemo } from 'react';
import { SlidersHorizontal, ChevronDown } from 'lucide-react';
import { products } from '@/lib/products-data';
import ProductCard from './ProductCard';

const categories = [
  'All',
  'Panjabi',
  'T-Shirt',
  'Shirt',
  'Trouser',
  'Drop Shoulder',
  'Winter Wear',
];

type SortOption = 'featured' | 'price-low' | 'price-high' | 'newest' | 'best-selling';

export default function ProductGrid() {
  const [activeCategory, setActiveCategory] = useState('All');
  const [sortOption, setSortOption] = useState<SortOption>('featured');
  const [visibleCount, setVisibleCount] = useState(8);

  const filtered = useMemo(() => {
    let list = activeCategory === 'All'
      ? [...products]
      : products.filter((p) => p.category === activeCategory);

    switch (sortOption) {
      case 'price-low':
        list.sort((a, b) => a.price - b.price);
        break;
      case 'price-high':
        list.sort((a, b) => b.price - a.price);
        break;
      case 'newest':
        list.sort((a, b) => b.id - a.id);
        break;
      case 'best-selling':
        list.sort((a, b) => b.reviews - a.reviews);
        break;
      default:
        break;
    }

    return list;
  }, [activeCategory, sortOption]);

  const visibleProducts = filtered.slice(0, visibleCount);
  const hasMore = visibleCount < filtered.length;

  const handleLoadMore = () => {
    setVisibleCount((prev) => prev + 6);
  };

  return (
    <section className="py-8 lg:py-12">
      {/* Heading */}
      <div className="mb-6 lg:mb-8">
        <h2 className="text-2xl lg:text-3xl font-bold text-gray-900">New Arrivals</h2>
        <p className="text-sm text-gray-500 mt-1">Discover the latest additions to our collection</p>
      </div>

      {/* Controls Row */}
      <div className="flex items-center justify-between gap-4 mb-6">
        {/* Category Pills */}
        <div className="flex-1 overflow-x-auto no-scrollbar">
          <div className="flex items-center gap-2 min-w-max">
            {categories.map((cat) => (
              <button
                key={cat}
                onClick={() => {
                  setActiveCategory(cat);
                  setVisibleCount(8);
                }}
                className={`px-4 py-2 rounded-full text-xs font-semibold whitespace-nowrap transition-all duration-200 ${
                  activeCategory === cat
                    ? 'bg-brand text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                {cat}
              </button>
            ))}
          </div>
        </div>

        {/* Sort Dropdown (desktop) */}
        <div className="hidden lg:flex items-center gap-2">
          <span className="text-xs text-gray-500">Sort by:</span>
          <div className="relative">
            <select
              value={sortOption}
              onChange={(e) => setSortOption(e.target.value as SortOption)}
              className="appearance-none bg-gray-100 text-gray-700 text-xs font-medium pl-3 pr-8 py-2 rounded-lg border-0 focus:ring-2 focus:ring-brand/30 cursor-pointer"
            >
              <option value="featured">Featured</option>
              <option value="price-low">Price Low-High</option>
              <option value="price-high">Price High-Low</option>
              <option value="newest">Newest</option>
              <option value="best-selling">Best Selling</option>
            </select>
            <ChevronDown className="absolute right-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none" />
          </div>
        </div>

        {/* Filter Toggle (mobile) */}
        <button className="lg:hidden flex items-center gap-1.5 px-3 py-2 bg-gray-100 rounded-lg text-xs font-medium text-gray-700 hover:bg-gray-200 transition-colors">
          <SlidersHorizontal className="w-3.5 h-3.5" />
          Filters
        </button>
      </div>

      {/* Product Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-5">
        {visibleProducts.map((product) => (
          <ProductCard key={product.id} product={product} />
        ))}
      </div>

      {/* Empty State */}
      {filtered.length === 0 && (
        <div className="text-center py-16">
          <p className="text-gray-400 text-sm">No products found in this category.</p>
        </div>
      )}

      {/* Load More */}
      {hasMore && (
        <div className="flex justify-center mt-8 lg:mt-10">
          <button
            onClick={handleLoadMore}
            className="border-2 border-brand text-brand px-8 py-2.5 rounded-xl text-sm font-semibold hover:bg-brand hover:text-white transition-all duration-300"
          >
            Load More
          </button>
        </div>
      )}
    </section>
  );
}
