'use client';

import React, { useState, useMemo } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import StoreLayout from '@/components/layout/StoreLayout';
import ProductCard from '@/components/ui/ProductCard';
import { useLanguage } from '@/context/LanguageContext';
import { products, categories } from '@/lib/data/products';
import styles from './products.module.css';

export default function ProductsPage() {
  const { t, language } = useLanguage();
  const searchParams = useSearchParams();
  const initialCategory = searchParams.get('category') || '';
  const initialQ = searchParams.get('q') || '';

  const [selectedCategory, setSelectedCategory] = useState(initialCategory);
  const [selectedBrand, setSelectedBrand] = useState('');
  const [priceRange, setPriceRange] = useState([0, 300]);
  const [sortBy, setSortBy] = useState('featured');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [searchQ, setSearchQ] = useState(initialQ);

  const brands = useMemo(() => [...new Set(products.map(p => p.brand))], []);

  const filtered = useMemo(() => {
    let list = [...products];
    if (selectedCategory) list = list.filter(p => p.category === selectedCategory);
    if (selectedBrand) list = list.filter(p => p.brand === selectedBrand);
    list = list.filter(p => p.price >= priceRange[0] && p.price <= priceRange[1]);
    if (searchQ) {
      const q = searchQ.toLowerCase();
      list = list.filter(p => p.name.toLowerCase().includes(q) || p.nameAr.includes(q) || p.brand.toLowerCase().includes(q));
    }
    switch (sortBy) {
      case 'price-asc': return list.sort((a, b) => a.price - b.price);
      case 'price-desc': return list.sort((a, b) => b.price - a.price);
      case 'rating': return list.sort((a, b) => b.rating - a.rating);
      case 'newest': return list.sort((a, b) => (b.isNew ? 1 : 0) - (a.isNew ? 1 : 0));
      default: return list.sort((a, b) => (b.isFeatured ? 1 : 0) - (a.isFeatured ? 1 : 0));
    }
  }, [selectedCategory, selectedBrand, priceRange, sortBy, searchQ]);

  return (
    <StoreLayout>
      <div className={styles.page}>
        <div className="container">
          {/* Header */}
          <div className={styles.pageHeader}>
            <div>
              <div className="breadcrumb" style={{ marginBottom: '8px' }}>
                <Link href="/" className="breadcrumb-link">{t.nav.home}</Link>
                <span className="breadcrumb-sep">›</span>
                <span className="breadcrumb-current">{t.nav.products}</span>
              </div>
              <h1 className={styles.pageTitle}>{t.nav.products}</h1>
              <p className="text-secondary" style={{ fontSize: '0.9rem' }}>{filtered.length} {language === 'ar' ? 'منتج' : 'products found'}</p>
            </div>
            {/* Search */}
            <input
              type="text"
              placeholder={t.header.search}
              value={searchQ}
              onChange={e => setSearchQ(e.target.value)}
              className="form-input"
              style={{ maxWidth: '320px' }}
            />
          </div>

          <div className={styles.layout}>
            {/* Sidebar Filters */}
            <aside className={styles.sidebar}>
              <div className={styles.filterGroup}>
                <div className={styles.filterTitle}>{t.categories.title}</div>
                <button className={`${styles.filterBtn} ${!selectedCategory ? styles.filterActive : ''}`} onClick={() => setSelectedCategory('')}>
                  {language === 'ar' ? 'الجميع' : 'All'} ({products.length})
                </button>
                {categories.map(c => (
                  <button key={c.id} className={`${styles.filterBtn} ${selectedCategory === c.id ? styles.filterActive : ''}`} onClick={() => setSelectedCategory(c.id)}>
                    {c.icon} {language === 'ar' ? c.nameAr : c.name} ({c.count})
                  </button>
                ))}
              </div>

              <div className={styles.filterGroup}>
                <div className={styles.filterTitle}>{language === 'ar' ? 'الماركة' : 'Brand'}</div>
                <button className={`${styles.filterBtn} ${!selectedBrand ? styles.filterActive : ''}`} onClick={() => setSelectedBrand('')}>
                  {language === 'ar' ? 'الجميع' : 'All'}
                </button>
                {brands.map(b => (
                  <button key={b} className={`${styles.filterBtn} ${selectedBrand === b ? styles.filterActive : ''}`} onClick={() => setSelectedBrand(b)}>
                    {b}
                  </button>
                ))}
              </div>

              <div className={styles.filterGroup}>
                <div className={styles.filterTitle}>
                  {language === 'ar' ? 'نطاق السعر' : 'Price Range'}
                  <span className={styles.priceDisplay}>0 – {priceRange[1]} KWD</span>
                </div>
                <input type="range" min="0" max="300" value={priceRange[1]} onChange={e => setPriceRange([0, Number(e.target.value)])} />
              </div>
            </aside>

            {/* Products Area */}
            <div className={styles.main}>
              {/* Toolbar */}
              <div className={styles.toolbar}>
                <select className="form-input" style={{ maxWidth: '200px', padding: '8px 12px' }} value={sortBy} onChange={e => setSortBy(e.target.value)}>
                  <option value="featured">{language === 'ar' ? 'المميزة أولاً' : 'Featured'}</option>
                  <option value="price-asc">{language === 'ar' ? 'السعر: الأدنى' : 'Price: Low to High'}</option>
                  <option value="price-desc">{language === 'ar' ? 'السعر: الأعلى' : 'Price: High to Low'}</option>
                  <option value="rating">{language === 'ar' ? 'الأعلى تقييماً' : 'Highest Rated'}</option>
                  <option value="newest">{language === 'ar' ? 'الأحدث' : 'Newest'}</option>
                </select>
                <div className={styles.viewToggle}>
                  <button className={`${styles.viewBtn} ${viewMode === 'grid' ? styles.viewActive : ''}`} onClick={() => setViewMode('grid')}>⊞</button>
                  <button className={`${styles.viewBtn} ${viewMode === 'list' ? styles.viewActive : ''}`} onClick={() => setViewMode('list')}>☰</button>
                </div>
              </div>

              {filtered.length === 0 ? (
                <div className={styles.empty}>
                  <div className={styles.emptyIcon}>🔍</div>
                  <div>{language === 'ar' ? 'لم يتم العثور على منتجات' : 'No products found'}</div>
                  <button className="btn btn-outline" onClick={() => { setSelectedCategory(''); setSelectedBrand(''); setSearchQ(''); }}>
                    {language === 'ar' ? 'إعادة ضبط الفلاتر' : 'Reset Filters'}
                  </button>
                </div>
              ) : (
                <div className={viewMode === 'grid' ? 'products-grid-wide' : styles.listGrid}>
                  {filtered.map(p => <ProductCard key={p.id} product={p} />)}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </StoreLayout>
  );
}
