import { useState, useEffect } from 'react';
import Head from 'next/head';
import Image from 'next/image';
import Link from 'next/link';
import { Heart, Search, Filter, ChevronDown, ChevronUp, X } from 'lucide-react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { productService, categoryService, Product, Category } from '../services/catalog';

export default function AllProductsPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [favorites, setFavorites] = useState<number[]>([]);
  const [hoveredProduct, setHoveredProduct] = useState<number | null>(null);
  
  // Состояние для фильтров
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [priceRange, setPriceRange] = useState<{ min: number | null; max: number | null }>({ min: null, max: null });
  const [showFilters, setShowFilters] = useState<boolean>(false);
  
  // Загрузка продуктов и категорий при монтировании компонента
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        
        // Загружаем категории
        const categoriesData = await categoryService.getCategories();
        setCategories(categoriesData);
        
        // Загружаем продукты с учетом фильтров
        const filters: any = {
          include_variants: true
        };
        
        if (searchTerm) {
          filters.search = searchTerm;
        }
        
        if (selectedCategory) {
          filters.category_id = selectedCategory;
        }
        
        if (priceRange.min !== null) {
          filters.min_price = priceRange.min;
        }
        
        if (priceRange.max !== null) {
          filters.max_price = priceRange.max;
        }
        
        const productsData = await productService.getProducts(filters);
        setProducts(productsData);
        setError(null);
      } catch (err) {
        console.error('Ошибка при загрузке данных:', err);
        setError('Не удалось загрузить данные. Пожалуйста, попробуйте позже.');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [searchTerm, selectedCategory, priceRange]);

  // Функция для добавления/удаления товара из избранного
  const toggleFavorite = (id: number, e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setFavorites(prev => 
      prev.includes(id) 
        ? prev.filter(itemId => itemId !== id) 
        : [...prev, id]
    );
  };

  // Функция для сброса всех фильтров
  const resetFilters = () => {
    setSearchTerm('');
    setSelectedCategory(null);
    setPriceRange({ min: null, max: null });
  };

  // Функция для форматирования цены
  const formatPrice = (price: number): string => {
    return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
  };

  // Получаем плоский список категорий для фильтра
  const flattenCategories = (categories: Category[], result: Category[] = []): Category[] => {
    categories.forEach(category => {
      result.push(category);
      if (category.subcategories && category.subcategories.length > 0) {
        flattenCategories(category.subcategories, result);
      }
    });
    return result;
  };

  const allCategories = flattenCategories(categories);

  return (
    <div className="min-h-screen bg-white font-['Arimo']">
      <Head>
        <title>Все товары | Brand Store</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Header />

      <main className="max-w-7xl mx-auto px-4 py-12 md:px-8">
        <h1 className="text-3xl font-bold mb-8 font-['Playfair_Display']">Все товары</h1>

        {/* Фильтры и поиск */}
        <div className="mb-8">
          <div className="flex flex-col md:flex-row gap-4 mb-4">
            <div className="relative flex-grow">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Search className="h-5 w-5 text-gray-400" />
              </div>
              <input
                type="text"
                placeholder="Поиск товаров..."
                className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              <Filter className="h-5 w-5 mr-2" />
              Фильтры
              {showFilters ? <ChevronUp className="ml-2 h-4 w-4" /> : <ChevronDown className="ml-2 h-4 w-4" />}
            </button>
          </div>

          {/* Расширенные фильтры */}
          {showFilters && (
            <div className="bg-white p-4 rounded-md shadow-md mb-4 border border-gray-200">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Категория</label>
                  <select
                    className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    value={selectedCategory || ''}
                    onChange={(e) => setSelectedCategory(e.target.value ? parseInt(e.target.value) : null)}
                  >
                    <option value="">Все категории</option>
                    {allCategories.map(category => (
                      <option key={category.id} value={category.id}>{category.name}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Минимальная цена</label>
                  <input
                    type="number"
                    className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    value={priceRange.min || ''}
                    onChange={(e) => setPriceRange({ ...priceRange, min: e.target.value ? parseInt(e.target.value) : null })}
                    placeholder="От"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Максимальная цена</label>
                  <input
                    type="number"
                    className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                    value={priceRange.max || ''}
                    onChange={(e) => setPriceRange({ ...priceRange, max: e.target.value ? parseInt(e.target.value) : null })}
                    placeholder="До"
                  />
                </div>
              </div>
              <div className="mt-4 flex justify-end">
                <button
                  onClick={resetFilters}
                  className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  <X className="h-4 w-4 mr-2" />
                  Сбросить фильтры
                </button>
              </div>
            </div>
          )}

          {/* Активные фильтры */}
          {(searchTerm || selectedCategory || priceRange.min || priceRange.max) && (
            <div className="flex flex-wrap gap-2 mb-4">
              {searchTerm && (
                <div className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-gray-100">
                  Поиск: {searchTerm}
                  <button onClick={() => setSearchTerm('')} className="ml-2">
                    <X className="h-4 w-4" />
                  </button>
                </div>
              )}
              {selectedCategory && (
                <div className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-gray-100">
                  Категория: {allCategories.find(c => c.id === selectedCategory)?.name}
                  <button onClick={() => setSelectedCategory(null)} className="ml-2">
                    <X className="h-4 w-4" />
                  </button>
                </div>
              )}
              {priceRange.min && (
                <div className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-gray-100">
                  От: {priceRange.min} ₽
                  <button onClick={() => setPriceRange({ ...priceRange, min: null })} className="ml-2">
                    <X className="h-4 w-4" />
                  </button>
                </div>
              )}
              {priceRange.max && (
                <div className="inline-flex items-center px-3 py-1 rounded-full text-sm bg-gray-100">
                  До: {priceRange.max} ₽
                  <button onClick={() => setPriceRange({ ...priceRange, max: null })} className="ml-2">
                    <X className="h-4 w-4" />
                  </button>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Отображение товаров */}
        {loading ? (
          <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
          </div>
        ) : error ? (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-6">
            <strong className="font-bold">Ошибка!</strong>
            <span className="block sm:inline"> {error}</span>
            <button 
              onClick={() => window.location.reload()} 
              className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              Попробовать снова
            </button>
          </div>
        ) : products.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-lg text-gray-600">Товары не найдены. Попробуйте изменить параметры поиска.</p>
            {(searchTerm || selectedCategory || priceRange.min || priceRange.max) && (
              <button 
                onClick={resetFilters}
                className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Сбросить все фильтры
              </button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            {products.map((product) => (
              <div key={product.id} className="group">
                <Link
                  href={`/product/${product.slug}`}
                  className="block"
                  onMouseEnter={() => setHoveredProduct(product.id)}
                  onMouseLeave={() => setHoveredProduct(null)}
                >
                  <div className="relative overflow-hidden rounded-xl">
                    <div className="aspect-[3/4] relative overflow-hidden rounded-xl">
                      {product.images && product.images.length > 0 ? (
                        <Image
                          src={
                            hoveredProduct === product.id && product.images.length > 1 
                              ? product.images[1]?.url || product.images[0]?.url 
                              : product.images[0]?.url
                          }
                          alt={product.name}
                          fill
                          sizes="(max-width: 640px) 100vw, (max-width: 768px) 50vw, (max-width: 1024px) 33vw, 25vw"
                          className="object-cover transition-all duration-500 group-hover:scale-105"
                        />
                      ) : (
                        <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                          <span className="text-gray-500">Нет изображения</span>
                        </div>
                      )}
                      <button
                        onClick={(e) => toggleFavorite(product.id, e)}
                        className="absolute top-4 right-4 bg-white/80 hover:bg-white rounded-full p-2 transition-all"
                        aria-label={favorites.includes(product.id) ? "Удалить из избранного" : "Добавить в избранное"}
                      >
                        <Heart
                          className={`w-5 h-5 ${favorites.includes(product.id) ? "fill-red-500 text-red-500" : "text-gray-700"}`}
                        />
                      </button>
                    </div>
                  </div>
                  <div className="mt-4">
                    <h3 className="text-lg font-medium">{product.name}</h3>
                    {product.variants && product.variants.length > 0 ? (
                      <p className="mt-1 text-lg font-bold">
                        {formatPrice(product.variants[0].price)} ₽
                        {product.variants[0].discount_price && (
                          <span className="ml-2 text-sm line-through text-gray-500">
                            {formatPrice(product.variants[0].discount_price)} ₽
                          </span>
                        )}
                      </p>
                    ) : (
                      <p className="mt-1 text-lg font-bold">Цена по запросу</p>
                    )}
                  </div>
                </Link>
              </div>
            ))}
          </div>
        )}
      </main>

      <Footer />
    </div>
  );
} 