"use client"

import { useState, useEffect } from "react"
import Image from "next/image"
import Link from "next/link"
import { ChevronDown, ChevronUp, X, Sliders, Search, ArrowUpRight } from "lucide-react"
import { ProductCard } from "@/components/ui/product-card"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { Slider } from "@/components/ui/slider"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
  SheetClose,
} from "@/components/ui/sheet"
import { motion, AnimatePresence } from "framer-motion"
import { Input } from "@/components/ui/input"
import { useInView } from "react-intersection-observer"
import { productService, categoryService, Product, Category, Collection } from "@/lib/catalog"
import { Skeleton } from "@/components/ui/skeleton"

export default function CatalogPage() {
  const [isFilterOpen, setIsFilterOpen] = useState(false)
  const [priceRange, setPriceRange] = useState([0, 15000])
  const [activeFilters, setActiveFilters] = useState<string[]>([])
  const [searchQuery, setSearchQuery] = useState("")
  const [sortOption, setSortOption] = useState("popular")
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid")
  const [currentPage, setCurrentPage] = useState(1)
  const [heroRef, heroInView] = useInView({ triggerOnce: true, threshold: 0.1 })
  const [selectedImage, setSelectedImage] = useState<number | null>(null)
  const [isMobile, setIsMobile] = useState(false)
  
  // Состояния для реальных данных
  const [products, setProducts] = useState<Product[]>([])
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [totalProducts, setTotalProducts] = useState(0)
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null)

  // Цвета (оставляем как есть, так как они не меняются)
  const colors = [
    { id: "black", name: "Черный", hex: "#000000" },
    { id: "white", name: "Белый", hex: "#FFFFFF" },
    { id: "beige", name: "Бежевый", hex: "#F5F5DC" },
    { id: "blue", name: "Синий", hex: "#0000FF" },
    { id: "green", name: "Зеленый", hex: "#008000" },
    { id: "red", name: "Красный", hex: "#FF0000" },
  ]

  // Размеры (оставляем как есть, так как они не меняются)
  const sizes = ["XS", "S", "M", "L", "XL", "XXL"]

  // Проверка размера экрана
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth < 768)
      // Автоматически переключаем на сетку на мобильных устройствах
      if (window.innerWidth < 640 && viewMode === 'list') {
        setViewMode('grid')
      }
    }
    
    checkIsMobile()
    window.addEventListener('resize', checkIsMobile)
    
    return () => {
      window.removeEventListener('resize', checkIsMobile)
    }
  }, [viewMode])

  // Загрузка категорий
  useEffect(() => {
    const loadCategories = async () => {
      try {
        const categoriesData = await categoryService.getCategories();
        setCategories(categoriesData);
      } catch (err) {
        console.error("Ошибка при загрузке категорий:", err);
        setError("Не удалось загрузить категории");
      }
    };

    loadCategories();
  }, []);

  // Загрузка продуктов с учетом фильтров
  useEffect(() => {
    const loadProducts = async () => {
      try {
        setLoading(true);
        
        // Формируем параметры запроса
        const params: any = {
          limit: 12,
          skip: (currentPage - 1) * 12,
          include_variants: true
        };
        
        // Добавляем фильтр по категории
        if (selectedCategory) {
          params.category_id = selectedCategory;
        }
        
        // Добавляем фильтр по цене
        if (priceRange[0] > 0) {
          params.min_price = priceRange[0];
        }
        if (priceRange[1] < 15000) {
          params.max_price = priceRange[1];
        }
        
        // Добавляем поисковый запрос
        if (searchQuery) {
          params.search = searchQuery;
        }
        
        const productsData = await productService.getProducts(params);
        
        // Сортировка полученных продуктов
        let sortedProducts = [...productsData];
        
        switch (sortOption) {
          case 'price_asc':
            sortedProducts.sort((a, b) => {
              const priceA = a.variants?.[0]?.price || 0;
              const priceB = b.variants?.[0]?.price || 0;
              return priceA - priceB;
            });
            break;
          case 'price_desc':
            sortedProducts.sort((a, b) => {
              const priceA = a.variants?.[0]?.price || 0;
              const priceB = b.variants?.[0]?.price || 0;
              return priceB - priceA;
            });
            break;
          case 'newest':
            sortedProducts.sort((a, b) => {
              const dateA = new Date((a as any).created_at || '').getTime();
              const dateB = new Date((b as any).created_at || '').getTime();
              return dateB - dateA;
            });
            break;
          default: // popular - оставляем как есть
            break;
        }
        
        setProducts(sortedProducts);
        setTotalProducts(productsData.length);
        setLoading(false);
      } catch (err) {
        console.error("Ошибка при загрузке продуктов:", err);
        setError("Не удалось загрузить продукты");
        setLoading(false);
      }
    };

    loadProducts();
  }, [currentPage, selectedCategory, priceRange, searchQuery, sortOption]);

  // Функция для переключения фильтров
  const toggleFilter = (filter: string) => {
    if (activeFilters.includes(filter)) {
      setActiveFilters(activeFilters.filter(f => f !== filter))
    } else {
      setActiveFilters([...activeFilters, filter])
    }
  }

  // Функция для очистки всех фильтров
  const clearAllFilters = () => {
    setActiveFilters([])
    setPriceRange([0, 15000])
    setSearchQuery("")
    setSelectedCategory(null)
  }

  // Обработчик выбора категории
  const handleCategorySelect = (categoryId: number) => {
    setSelectedCategory(categoryId === selectedCategory ? null : categoryId);
    setCurrentPage(1); // Сбрасываем страницу на первую при изменении категории
  };

  // Компонент боковой панели фильтров
  const FilterSidebar = () => (
    <div className="space-y-8">
      {/* Поиск */}
      <div className="mb-6">
        <div className="relative">
          <Input
            type="search"
            placeholder="Поиск..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 border-primary/20 focus:border-primary rounded-none"
          />
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-primary/60" />
        </div>
      </div>

      {/* Категории */}
      <div>
        <Accordion type="single" collapsible defaultValue="categories">
          <AccordionItem value="categories" className="border-b-0">
            <AccordionTrigger className="font-medium text-base py-2">Категории</AccordionTrigger>
            <AccordionContent>
              <div className="mt-2 space-y-2">
                {categories.map((category) => (
                  <div key={category.id} className="flex items-center">
                    <Checkbox 
                      id={`category-${category.id}`}
                      checked={selectedCategory === category.id} 
                      onCheckedChange={() => handleCategorySelect(category.id)}
                      className="mr-2"
                    />
                    <Label 
                      htmlFor={`category-${category.id}`}
                      className="text-sm flex-1 cursor-pointer"
                    >
                      {category.name}
                    </Label>
                    <span className="text-sm text-primary/60">
                      {category.products_count || 0}
                    </span>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* Цена */}
      <div>
        <Accordion type="single" collapsible defaultValue="price">
          <AccordionItem value="price" className="border-b-0">
            <AccordionTrigger className="font-medium text-base py-2">Цена</AccordionTrigger>
            <AccordionContent>
              <div className="px-1 py-4">
                <Slider
                  value={priceRange}
                  min={0}
                  max={15000}
                  step={100}
                  onValueChange={(value) => setPriceRange(value as [number, number])}
                  className="mb-6"
                />
                <div className="flex justify-between text-sm">
                  <div>
                    <span className="text-primary/60 mr-1">от</span>
                    <span className="font-medium">{priceRange[0]} ₽</span>
                  </div>
                  <div>
                    <span className="text-primary/60 mr-1">до</span>
                    <span className="font-medium">{priceRange[1]} ₽</span>
                  </div>
                </div>
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* Цвета */}
      <div>
        <Accordion type="single" collapsible>
          <AccordionItem value="colors" className="border-b-0">
            <AccordionTrigger className="font-medium text-base py-2">Цвет</AccordionTrigger>
            <AccordionContent>
              <div className="grid grid-cols-3 gap-2 mt-2">
                {colors.map((color) => (
                  <div key={color.id} className="flex flex-col items-center">
                    <button
                      className={`relative w-8 h-8 rounded-full mb-1 ${
                        activeFilters.includes(color.id)
                          ? "ring-2 ring-primary ring-offset-2"
                          : ""
                      }`}
                      style={{ backgroundColor: color.hex }}
                      onClick={() => toggleFilter(color.id)}
                    >
                      {activeFilters.includes(color.id) && (
                        <span
                          className={`absolute inset-0 flex items-center justify-center ${
                            color.id === "white" ? "text-black" : "text-white"
                          }`}
                        >
                          ✓
                        </span>
                      )}
                    </button>
                    <span className="text-xs">{color.name}</span>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* Размеры */}
      <div>
        <Accordion type="single" collapsible>
          <AccordionItem value="sizes" className="border-b-0">
            <AccordionTrigger className="font-medium text-base py-2">Размер</AccordionTrigger>
            <AccordionContent>
              <div className="grid grid-cols-3 gap-2 mt-2">
                {sizes.map((size) => (
                  <button
                    key={size}
                    className={`border py-2 text-sm text-center transition-colors ${
                      activeFilters.includes(size)
                        ? "bg-primary text-white border-primary"
                        : "border-gray-300 hover:border-primary"
                    }`}
                    onClick={() => toggleFilter(size)}
                  >
                    {size}
                  </button>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* Кнопка сброса фильтров */}
      <Button variant="outline" className="w-full" onClick={clearAllFilters}>
        Сбросить фильтры
      </Button>
    </div>
  )

  // Отображаем загрузку
  if (loading && currentPage === 1) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-3xl font-medium">Каталог товаров</h1>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} className="space-y-2">
              <Skeleton className="h-64 w-full" />
              <Skeleton className="h-4 w-3/4" />
              <Skeleton className="h-4 w-1/2" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  // Отображаем ошибку, если она есть
  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="bg-red-100 p-4 rounded-md text-red-700">
          <p className="font-medium">Ошибка загрузки данных</p>
          <p>{error}</p>
          <Button 
            className="mt-4" 
            onClick={() => window.location.reload()}
          >
            Попробовать снова
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      {/* Заголовок и фильтры для десктопа */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 space-y-4 md:space-y-0">
        <div>
          <h1 className="text-3xl font-medium">Каталог товаров</h1>
          <p className="text-primary/60">Найдено товаров: {totalProducts}</p>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          {/* Сортировка */}
          <Select value={sortOption} onValueChange={setSortOption}>
            <SelectTrigger className="w-[180px] text-sm">
              <SelectValue placeholder="Сортировка" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="popular">По популярности</SelectItem>
              <SelectItem value="price_asc">По возрастанию цены</SelectItem>
              <SelectItem value="price_desc">По убыванию цены</SelectItem>
              <SelectItem value="newest">Сначала новые</SelectItem>
            </SelectContent>
          </Select>

          {/* Переключатель вид сетки/списка */}
          <div className="border rounded-md flex">
            <button
              className={`px-3 py-2 ${viewMode === "grid" ? "bg-gray-100" : ""}`}
              onClick={() => setViewMode("grid")}
              title="Сетка"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="2" y="2" width="9" height="9" rx="1" className={viewMode === "grid" ? "fill-primary" : "fill-gray-500"} />
                <rect x="13" y="2" width="9" height="9" rx="1" className={viewMode === "grid" ? "fill-primary" : "fill-gray-500"} />
                <rect x="2" y="13" width="9" height="9" rx="1" className={viewMode === "grid" ? "fill-primary" : "fill-gray-500"} />
                <rect x="13" y="13" width="9" height="9" rx="1" className={viewMode === "grid" ? "fill-primary" : "fill-gray-500"} />
              </svg>
            </button>
            <button
              className={`px-3 py-2 ${viewMode === "list" ? "bg-gray-100" : ""}`}
              onClick={() => setViewMode("list")}
              title="Список"
              disabled={isMobile}
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="2" y="4" width="20" height="2" rx="1" className={viewMode === "list" ? "fill-primary" : "fill-gray-500"} />
                <rect x="2" y="11" width="20" height="2" rx="1" className={viewMode === "list" ? "fill-primary" : "fill-gray-500"} />
                <rect x="2" y="18" width="20" height="2" rx="1" className={viewMode === "list" ? "fill-primary" : "fill-gray-500"} />
              </svg>
            </button>
          </div>

          {/* Кнопка фильтров для мобильных */}
          <Sheet>
            <SheetTrigger asChild>
              <Button variant="outline" className="md:hidden flex items-center gap-2" onClick={() => setIsFilterOpen(true)}>
                <Sliders className="h-4 w-4" />
                Фильтры
                {activeFilters.length > 0 && (
                  <span className="bg-primary text-white rounded-full w-5 h-5 flex items-center justify-center text-xs">
                    {activeFilters.length}
                  </span>
                )}
              </Button>
            </SheetTrigger>
            <SheetContent side="left">
              <SheetHeader>
                <SheetTitle>Фильтры</SheetTitle>
                <SheetDescription>
                  Выберите параметры для фильтрации товаров
                </SheetDescription>
              </SheetHeader>
              <div className="py-4">
                <FilterSidebar />
              </div>
            </SheetContent>
          </Sheet>
        </div>
      </div>

      {/* Активные фильтры */}
      {activeFilters.length > 0 && (
        <div className="mb-6">
          <div className="flex flex-wrap gap-2">
            {activeFilters.map((filter) => (
              <Button key={filter} size="sm" variant="outline" className="h-8 flex items-center gap-1" onClick={() => toggleFilter(filter)}>
                {filter}
                <X className="h-3 w-3" />
              </Button>
            ))}
            <Button size="sm" variant="ghost" className="h-8" onClick={clearAllFilters}>
              Очистить все
            </Button>
          </div>
        </div>
      )}

      {/* Основное содержимое */}
      <div className="flex flex-col md:flex-row gap-8">
        {/* Боковая панель с фильтрами - десктоп */}
        <div className="w-full md:w-64 hidden md:block space-y-6">
          <FilterSidebar />
        </div>

        {/* Список товаров */}
        <div className="flex-1">
          {/* Сетка товаров */}
          {products.length > 0 ? (
            <div
              className={
                viewMode === "grid"
                  ? "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-6"
                  : "flex flex-col space-y-6"
              }
            >
              {products.map((product) => (
                <AnimatePresence key={product.id}>
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: 20 }}
                    transition={{ duration: 0.3 }}
                  >
                    {viewMode === "grid" ? (
                      // Карточка товара в режиме сетки
                      <ProductCard
                        key={product.id}
                        id={product.id}
                        name={product.name}
                        price={product.variants?.[0]?.price || 0}
                        salePrice={product.variants?.[0]?.discount_price || undefined}
                        image={product.images && product.images.length > 0 ? 
                          product.images[0].url : "/placeholder.svg?height=600&width=400"}
                        slug={product.slug}
                        isNew={false} // Нужно добавить поле в API
                        isOnSale={product.variants?.[0]?.discount_price ? true : false}
                        category={product.category?.name || ""}
                      />
                    ) : (
                      // Карточка товара в режиме списка
                      <div className="flex flex-col md:flex-row border border-gray-200 rounded-lg overflow-hidden">
                        <div className="w-full md:w-1/3 relative overflow-hidden group">
                          <Link href={`/catalog/${product.slug}`}>
                            <div className="aspect-[3/4] relative">
                              <Image
                                src={product.images && product.images.length > 0 ? 
                                  (product.images[0].url.startsWith('http') ? 
                                    product.images[0].url : 
                                    `${process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:8000'}${product.images[0].url}`) : 
                                  "/placeholder.svg?height=600&width=400"}
                                alt={product.name}
                                className="object-cover w-full h-full"
                                width={400}
                                height={600}
                              />
                            </div>
                          </Link>
                          {product.variants?.[0]?.discount_price && (
                            <div className="absolute top-2 left-2 bg-red-600 text-white px-2 py-1 text-xs font-medium">
                              Скидка
                            </div>
                          )}
                        </div>
                        <div className="w-full md:w-2/3 p-6 flex flex-col justify-between">
                          <div>
                            <Link href={`/catalog/${product.slug}`}>
                              <h3 className="text-xl font-medium">{product.name}</h3>
                            </Link>
                            <p className="text-primary/60 mt-2">
                              {product.category?.name || ''}
                            </p>
                            <p className="mt-4 text-sm">{product.description.length > 150 
                              ? `${product.description.substring(0, 150)}...` 
                              : product.description}</p>
                          </div>
                          <div className="mt-4 flex items-center justify-between">
                            <div>
                              {product.variants?.[0]?.discount_price ? (
                                <div className="flex items-center gap-2">
                                  <span className="text-lg font-medium">{product.variants[0]?.discount_price} ₽</span>
                                  <span className="text-sm text-primary/60 line-through">{product.variants[0]?.price} ₽</span>
                                </div>
                              ) : (
                                <span className="text-lg font-medium">{product.variants?.[0]?.price || 0} ₽</span>
                              )}
                            </div>
                            <Link href={`/catalog/${product.slug}`}>
                              <Button>Подробнее</Button>
                            </Link>
                          </div>
                        </div>
                      </div>
                    )}
                  </motion.div>
                </AnimatePresence>
              ))}
            </div>
          ) : (
            // Если товары не найдены
            <div className="bg-gray-50 p-8 rounded-lg text-center">
              <h3 className="text-xl font-medium mb-2">Товары не найдены</h3>
              <p className="text-primary/60 mb-4">
                Попробуйте изменить параметры фильтрации или поиска
              </p>
              <Button onClick={clearAllFilters}>Сбросить фильтры</Button>
            </div>
          )}

          {/* Пагинация */}
          {totalProducts > 0 && (
            <div className="mt-12 flex justify-center">
              <div className="flex space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                  disabled={currentPage === 1}
                >
                  Назад
                </Button>
                {/* Номера страниц */}
                {Array.from({ length: Math.ceil(totalProducts / 12) }).map((_, i) => (
                  <Button
                    key={i}
                    variant={currentPage === i + 1 ? "default" : "outline"}
                    size="sm"
                    onClick={() => setCurrentPage(i + 1)}
                    className={currentPage === i + 1 ? "bg-primary text-white" : ""}
                  >
                    {i + 1}
                  </Button>
                ))}
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(Math.min(Math.ceil(totalProducts / 12), currentPage + 1))}
                  disabled={currentPage === Math.ceil(totalProducts / 12)}
                >
                  Вперед
                </Button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
