import React, { useState, useMemo } from 'react';
import { Search, Filter, SlidersHorizontal, ArrowUpDown, RefreshCw, ShoppingBag, X } from 'lucide-react';
import type { Product, Category, FilterOptions } from '../types';
import { ProductCard } from './ProductCard';
import { toPersianDigits, formatPrice } from '../utils/formatters';

interface ShopViewProps {
  products: Product[];
  categories: Category[];
  selectedCategoryId?: string;
  initialSearch?: string;
  onSelectCategory: (categoryId: string) => void;
  onViewProductDetails: (product: Product) => void;
}

export const ShopView: React.FC<ShopViewProps> = ({
  products,
  categories,
  selectedCategoryId,
  initialSearch,
  onSelectCategory,
  onViewProductDetails,
}) => {
  const [search, setSearch] = useState(initialSearch || '');
  const [sort, setSort] = useState<'newest' | 'price_asc' | 'price_desc' | 'popular' | 'discount'>('newest');
  const [inStockOnly, setInStockOnly] = useState(false);
  const [maxPriceFilter, setMaxPriceFilter] = useState<number>(2000000);
  const [showMobileFilters, setShowMobileFilters] = useState(false);
  const [visibleCount, setVisibleCount] = useState(12);

  // Filter & Sort products in memory
  const filteredProducts = useMemo(() => {
    let list = [...products];

    if (selectedCategoryId) {
      list = list.filter(p => p.categoryId === selectedCategoryId);
    }

    if (search.trim()) {
      const q = search.toLowerCase().trim();
      list = list.filter(p =>
        p.title.toLowerCase().includes(q) ||
        p.description.toLowerCase().includes(q) ||
        p.tags?.some(t => t.toLowerCase().includes(q))
      );
    }

    if (inStockOnly) {
      list = list.filter(p => p.inStock);
    }

    if (maxPriceFilter > 0) {
      list = list.filter(p => p.price <= maxPriceFilter);
    }

    // Sort
    switch (sort) {
      case 'price_asc':
        list.sort((a, b) => a.price - b.price);
        break;
      case 'price_desc':
        list.sort((a, b) => b.price - a.price);
        break;
      case 'popular':
        list.sort((a, b) => (b.isBestSeller ? 1 : 0) - (a.isBestSeller ? 1 : 0));
        break;
      case 'discount':
        list.sort((a, b) => (b.discountPercent || 0) - (a.discountPercent || 0));
        break;
      case 'newest':
      default:
        list.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
        break;
    }

    return list;
  }, [products, selectedCategoryId, search, inStockOnly, maxPriceFilter, sort]);

  const displayedProducts = filteredProducts.slice(0, visibleCount);

  const resetFilters = () => {
    setSearch('');
    onSelectCategory('');
    setInStockOnly(false);
    setMaxPriceFilter(2000000);
    setSort('newest');
  };

  return (
    <div className="py-8 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-right space-y-8">
      
      {/* Page Title & Breadcrumb */}
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4 border-b border-purple-900/30 pb-6">
        <div>
          <h1 className="text-2xl sm:text-3xl font-black text-white">
            فروشگاه سرویس‌های WireGuard ZaccShop
          </h1>
          <p className="text-xs sm:text-sm text-zinc-400 mt-1">
            پلن‌های WireGuard برای یک کاربر با حجم و مدت‌زمان مشخص
          </p>
        </div>

        <div className="text-xs font-semibold text-purple-300 bg-[#140c28] px-3.5 py-2 rounded-xl border border-purple-500/20 self-start md:self-auto">
          نمایش {toPersianDigits(filteredProducts.length)} پلن فعال
        </div>
      </div>

      {/* Main Layout (Sidebar Filters + Products Grid) */}
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">
        
        {/* Mobile Filters Trigger */}
        <div className="lg:hidden flex items-center gap-2">
          <button
            onClick={() => setShowMobileFilters(!showMobileFilters)}
            className="flex-1 py-2.5 px-4 rounded-xl bg-[#140c2a] border border-purple-500/30 text-xs font-bold text-zinc-200 flex items-center justify-center gap-2"
          >
            <SlidersHorizontal className="w-4 h-4 text-purple-400" />
            <span>فیلتر پلن‌ها</span>
          </button>
        </div>

        {/* Sidebar Filters */}
        <aside className={`lg:block ${showMobileFilters ? 'block' : 'hidden'} lg:col-span-1 bg-[#120b24] p-5 rounded-2xl border border-purple-500/20 space-y-6 shadow-xl`}>
          
          <div className="flex items-center justify-between border-b border-purple-900/40 pb-3">
            <h3 className="font-bold text-sm text-white flex items-center gap-2">
              <Filter className="w-4 h-4 text-purple-400" />
              فیلترهای پیشرفته
            </h3>
            <button
              onClick={resetFilters}
              className="text-[11px] text-purple-400 hover:text-purple-300 font-semibold"
            >
              حذف فیلترها
            </button>
          </div>

          {/* Search Box */}
          <div className="space-y-1.5">
            <label className="text-xs font-bold text-zinc-300">جستجو در فروشگاه:</label>
            <div className="relative">
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="نام پلن WireGuard..."
                className="w-full bg-[#0c071a] text-xs text-zinc-100 placeholder-zinc-500 pr-8 pl-3 py-2.5 rounded-xl border border-purple-500/20 focus:outline-none focus:border-purple-500"
              />
              <Search className="w-3.5 h-3.5 text-purple-400 absolute right-2.5 top-1/2 -translate-y-1/2" />
            </div>
          </div>

          {/* Categories Filter */}
          <div className="space-y-2">
            <label className="text-xs font-bold text-zinc-300">دسته‌بندی:</label>
            <div className="flex flex-col gap-1">
              <button
                onClick={() => onSelectCategory('')}
                className={`text-right px-3 py-2 rounded-xl text-xs font-medium transition-all ${
                  !selectedCategoryId
                    ? 'bg-purple-600 text-white font-bold shadow-md'
                    : 'text-zinc-300 hover:bg-purple-900/30'
                }`}
              >
                همه دسته‌بندی‌ها
              </button>

              {categories.map((cat) => (
                <button
                  key={cat.id}
                  onClick={() => onSelectCategory(cat.id)}
                  className={`text-right px-3 py-2 rounded-xl text-xs font-medium transition-all flex items-center justify-between ${
                    selectedCategoryId === cat.id
                      ? 'bg-purple-600 text-white font-bold shadow-md'
                      : 'text-zinc-300 hover:bg-purple-900/30'
                  }`}
                >
                  <span>{cat.name}</span>
                  {cat.productCount !== undefined && (
                    <span className="text-[10px] opacity-70">
                      ({toPersianDigits(cat.productCount)})
                    </span>
                  )}
                </button>
              ))}
            </div>
          </div>

          {/* Price Range Slider */}
          <div className="space-y-2 pt-2 border-t border-purple-900/30">
            <div className="flex justify-between text-xs">
              <span className="font-bold text-zinc-300">حداکثر قیمت:</span>
              <span className="text-purple-300 font-semibold">{formatPrice(maxPriceFilter)}</span>
            </div>
            <input
              type="range"
              min={100000}
              max={2000000}
              step={50000}
              value={maxPriceFilter}
              onChange={(e) => setMaxPriceFilter(Number(e.target.value))}
              className="w-full accent-purple-500 bg-purple-950/60 rounded-lg cursor-pointer"
            />
            <div className="flex justify-between text-[10px] text-zinc-500">
              <span>۱۰۰ هزار تومان</span>
              <span>۲ میلیون تومان</span>
            </div>
          </div>

          {/* In Stock Toggle */}
          <div className="pt-2 border-t border-purple-900/30">
            <label className="flex items-center justify-between cursor-pointer">
              <span className="text-xs font-semibold text-zinc-300">فقط کالاهای موجود</span>
              <input
                type="checkbox"
                checked={inStockOnly}
                onChange={(e) => setInStockOnly(e.target.checked)}
                className="w-4 h-4 accent-purple-500 rounded cursor-pointer"
              />
            </label>
          </div>

        </aside>

        {/* Products Grid Area */}
        <div className="lg:col-span-3 space-y-6">
          
          {/* Top Sort Controls */}
          <div className="bg-[#120b24] p-3.5 rounded-2xl border border-purple-500/20 flex flex-wrap items-center justify-between gap-3 text-xs">
            <div className="flex items-center gap-2 text-zinc-400">
              <ArrowUpDown className="w-4 h-4 text-purple-400" />
              <span>مرتب‌سازی بر اساس:</span>
            </div>

            <div className="flex flex-wrap items-center gap-1.5">
              {[
                { id: 'newest', label: 'جدیدترین' },
                { id: 'popular', label: 'پرفروش‌ترین' },
                { id: 'discount', label: 'بیشترین تخفیف' },
                { id: 'price_asc', label: 'ارزان‌ترین' },
                { id: 'price_desc', label: 'گران‌ترین' },
              ].map((s) => (
                <button
                  key={s.id}
                  onClick={() => setSort(s.id as any)}
                  className={`px-3 py-1.5 rounded-lg transition-all ${
                    sort === s.id
                      ? 'bg-purple-600 text-white font-bold shadow'
                      : 'bg-[#170e30] text-zinc-400 hover:text-zinc-200 hover:bg-[#201442]'
                  }`}
                >
                  {s.label}
                </button>
              ))}
            </div>
          </div>

          {/* Products Grid */}
          {displayedProducts.length === 0 ? (
            <div className="py-20 text-center space-y-4 bg-[#120b24] rounded-2xl border border-purple-500/15 p-8">
              <div className="w-16 h-16 rounded-2xl bg-[#170e30] border border-purple-500/20 mx-auto flex items-center justify-center text-purple-400">
                <ShoppingBag className="w-8 h-8 opacity-40" />
              </div>
              <div className="text-zinc-200 font-bold text-base">هیچ محصولی با این مشخصات یافت نشد</div>
              <p className="text-xs text-zinc-500 max-w-sm mx-auto">
                می‌توانید فیلترهای اعمال‌شده یا عبارت جستجوی خود را تغییر دهید تا نتایج نمایش داده شوند.
              </p>
              <button
                onClick={resetFilters}
                className="px-4 py-2 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-xs font-bold transition-colors"
              >
                پاک کردن همه فیلترها
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {displayedProducts.map((product) => (
                <ProductCard
                  key={product.id}
                  product={product}
                  onViewDetails={onViewProductDetails}
                />
              ))}
            </div>
          )}

          {/* Load More Button if remaining */}
          {filteredProducts.length > visibleCount && (
            <div className="text-center pt-4">
              <button
                onClick={() => setVisibleCount(c => c + 12)}
                className="px-6 py-3 rounded-xl bg-[#170e30] hover:bg-[#221448] text-purple-300 hover:text-white border border-purple-500/30 text-xs font-bold transition-all shadow-md"
              >
                نمایش محصولات بیشتر ({toPersianDigits(filteredProducts.length - visibleCount)} محصول باقی‌مانده)
              </button>
            </div>
          )}

        </div>

      </div>

    </div>
  );
};
