'use client';

import React, { useState, useMemo } from 'react';
import { useSearchParams } from 'next/navigation';
import {
  Search,
  Filter,
  SlidersHorizontal,
  Grid,
  X,
  Sparkles,
} from 'lucide-react';
import { Product, Category } from '@/types';
import ProductCard from '@/components/home/ProductCard';

interface ShopClientProps {
  initialProducts: Product[];
  categories: Category[];
}

export default function ShopClient({ initialProducts, categories }: ShopClientProps) {
  const searchParams = useSearchParams();
  const initialQuery = searchParams.get('query') || '';
  const initialCategory = searchParams.get('category') || 'all';
  const initialFilter = searchParams.get('filter') || 'all'; // free, trial, paid, all

  const [search, setSearch] = useState(initialQuery);
  const [selectedCategory, setSelectedCategory] = useState<string | number>(
    initialCategory === 'all' ? 'all' : Number(initialCategory) || initialCategory
  );
  const [priceFilter, setPriceFilter] = useState<'all' | 'free' | 'trial' | 'paid'>(
    (initialFilter as any) || 'all'
  );
  const [selectedTech, setSelectedTech] = useState<string>('all');
  const [sortBy, setSortBy] = useState<'newest' | 'price_low' | 'price_high' | 'rating' | 'popular'>('popular');

  // Extract all unique tech stacks from products
  const allTechStacks = useMemo(() => {
    const set = new Set<string>();
    initialProducts.forEach((p) => {
      p.tech_stacks.forEach((t) => set.add(t));
    });
    return Array.from(set);
  }, [initialProducts]);

  // Filtered & Sorted products
  const filteredProducts = useMemo(() => {
    return initialProducts
      .filter((p) => {
        // Search query
        if (search.trim()) {
          const q = search.toLowerCase();
          const matchesTitle = p.title.toLowerCase().includes(q);
          const matchesDesc = p.short_desc.toLowerCase().includes(q);
          const matchesTech = p.tech_stacks.some((t) => t.toLowerCase().includes(q));
          if (!matchesTitle && !matchesDesc && !matchesTech) return false;
        }

        // Category filter
        if (selectedCategory !== 'all') {
          if (String(p.category_id) !== String(selectedCategory)) return false;
        }

        // Price type filter
        if (priceFilter === 'free' && !p.is_free) return false;
        if (priceFilter === 'trial' && !p.has_trial) return false;
        if (priceFilter === 'paid' && (p.is_free || p.price === 0)) return false;

        // Tech stack
        if (selectedTech !== 'all') {
          if (!p.tech_stacks.includes(selectedTech)) return false;
        }

        return true;
      })
      .sort((a, b) => {
        if (sortBy === 'newest') {
          return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
        }
        if (sortBy === 'price_low') {
          return a.price - b.price;
        }
        if (sortBy === 'price_high') {
          return b.price - a.price;
        }
        if (sortBy === 'rating') {
          return b.rating - a.rating;
        }
        if (sortBy === 'popular') {
          return b.sales_count - a.sales_count;
        }
        return 0;
      });
  }, [initialProducts, search, selectedCategory, priceFilter, selectedTech, sortBy]);

  const resetFilters = () => {
    setSearch('');
    setSelectedCategory('all');
    setPriceFilter('all');
    setSelectedTech('all');
    setSortBy('popular');
  };

  const hasActiveFilters =
    search !== '' ||
    selectedCategory !== 'all' ||
    priceFilter !== 'all' ||
    selectedTech !== 'all';

  return (
    <div className="py-8 md:py-12 bg-gray-50 min-h-screen">
      <div className="container mx-auto px-4 max-w-7xl space-y-8">
        {/* Page Header */}
        <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-sm border border-gray-100 flex flex-col md:flex-row md:items-center justify-between gap-6">
          <div>
            <div className="inline-flex items-center gap-1.5 text-xs font-bold text-indigo-600 uppercase tracking-wider mb-1">
              <Sparkles className="w-4 h-4" />
              <span>Digital Catalog</span>
            </div>
            <h1 className="text-2xl sm:text-4xl font-extrabold text-gray-900">
              Browse All Scripts & Modules
            </h1>
            <p className="text-sm text-gray-500 mt-1">
              Showing {filteredProducts.length} results matching your criteria
            </p>
          </div>

          {/* Search box */}
          <div className="w-full md:w-80">
            <div className="relative">
              <input
                type="text"
                placeholder="Search products..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="w-full py-2.5 pl-10 pr-4 text-sm bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-600/20 focus:border-indigo-600 transition"
              />
              <Search className="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
              {search && (
                <button
                  onClick={() => setSearch('')}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  <X className="w-4 h-4" />
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Filters Toolbar */}
        <div className="bg-white rounded-2xl p-4 sm:p-5 shadow-sm border border-gray-100 space-y-4">
          {/* Top Row: Categories & Sort */}
          <div className="flex flex-wrap items-center justify-between gap-4">
            {/* Category Pills */}
            <div className="flex items-center gap-2 overflow-x-auto no-scrollbar pb-1 max-w-full">
              <button
                onClick={() => setSelectedCategory('all')}
                className={`px-3.5 py-1.5 rounded-xl text-xs font-semibold whitespace-nowrap transition ${
                  selectedCategory === 'all'
                    ? 'bg-indigo-600 text-white shadow-sm'
                    : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
                }`}
              >
                All Categories
              </button>
              {categories.map((c) => (
                <button
                  key={c.id}
                  onClick={() => setSelectedCategory(c.id)}
                  className={`px-3.5 py-1.5 rounded-xl text-xs font-semibold whitespace-nowrap transition ${
                    String(selectedCategory) === String(c.id)
                      ? 'bg-indigo-600 text-white shadow-sm'
                      : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
                  }`}
                >
                  {c.name}
                </button>
              ))}
            </div>

            {/* Sort Select */}
            <div className="flex items-center gap-2 shrink-0">
              <SlidersHorizontal className="w-4 h-4 text-gray-400" />
              <span className="text-xs text-gray-500 font-medium">Sort By:</span>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as any)}
                className="text-xs font-semibold bg-gray-50 border border-gray-200 rounded-lg px-3 py-1.5 focus:outline-none focus:border-indigo-600 text-gray-800"
              >
                <option value="popular">Most Popular</option>
                <option value="newest">Newest First</option>
                <option value="price_low">Price: Low to High</option>
                <option value="price_high">Price: High to Low</option>
                <option value="rating">Top Rated</option>
              </select>
            </div>
          </div>

          {/* Bottom Row: Price Type & Tech Stacks */}
          <div className="pt-3 border-t border-gray-100 flex flex-wrap items-center justify-between gap-4">
            {/* Price Type Segmented Buttons */}
            <div className="flex items-center gap-1.5 bg-gray-100 p-1 rounded-xl">
              <button
                onClick={() => setPriceFilter('all')}
                className={`px-3 py-1 text-xs font-semibold rounded-lg transition ${
                  priceFilter === 'all' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                All
              </button>
              <button
                onClick={() => setPriceFilter('free')}
                className={`px-3 py-1 text-xs font-semibold rounded-lg transition ${
                  priceFilter === 'free' ? 'bg-emerald-500 text-white shadow-sm' : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                Free
              </button>
              <button
                onClick={() => setPriceFilter('trial')}
                className={`px-3 py-1 text-xs font-semibold rounded-lg transition ${
                  priceFilter === 'trial' ? 'bg-blue-600 text-white shadow-sm' : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                Free Trial
              </button>
              <button
                onClick={() => setPriceFilter('paid')}
                className={`px-3 py-1 text-xs font-semibold rounded-lg transition ${
                  priceFilter === 'paid' ? 'bg-indigo-600 text-white shadow-sm' : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                Paid
              </button>
            </div>

            {/* Tech Stack filter pills */}
            <div className="flex items-center gap-1.5 overflow-x-auto no-scrollbar max-w-full">
              <span className="text-xs text-gray-400 font-medium mr-1">Stack:</span>
              <button
                onClick={() => setSelectedTech('all')}
                className={`px-2.5 py-1 text-[11px] font-semibold rounded-md transition ${
                  selectedTech === 'all' ? 'bg-indigo-100 text-indigo-700' : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
                }`}
              >
                All
              </button>
              {allTechStacks.map((tech) => (
                <button
                  key={tech}
                  onClick={() => setSelectedTech(tech === selectedTech ? 'all' : tech)}
                  className={`px-2.5 py-1 text-[11px] font-semibold rounded-md transition ${
                    selectedTech === tech
                      ? 'bg-indigo-600 text-white shadow-sm'
                      : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
                  }`}
                >
                  {tech}
                </button>
              ))}
            </div>

            {/* Reset Button */}
            {hasActiveFilters && (
              <button
                onClick={resetFilters}
                className="text-xs font-semibold text-red-600 hover:text-red-700 flex items-center gap-1"
              >
                <X className="w-3.5 h-3.5" />
                Reset Filters
              </button>
            )}
          </div>
        </div>

        {/* Product Grid */}
        {filteredProducts.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {filteredProducts.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        ) : (
          <div className="bg-white rounded-3xl p-12 text-center border border-gray-100 space-y-4">
            <div className="w-16 h-16 rounded-full bg-gray-100 text-gray-400 flex items-center justify-center mx-auto">
              <Search className="w-8 h-8" />
            </div>
            <h3 className="text-lg font-bold text-gray-800">No matching products found</h3>
            <p className="text-xs text-gray-500 max-w-sm mx-auto">
              Try adjusting your search query, clearing filters, or browsing other categories.
            </p>
            <button
              onClick={resetFilters}
              className="px-5 py-2.5 bg-indigo-600 text-white text-xs font-semibold rounded-xl hover:bg-indigo-700 transition"
            >
              Clear All Filters
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
