"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"

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)

  // Проверка размера экрана
  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])

  // Mock products data
  const products = [
    {
      id: 1,
      name: "ПЛАТЬЕ С ЦВЕТОЧНЫМ ПРИНТОМ",
      price: 5990,
      salePrice: 4490,
      image: "/placeholder.svg?height=600&width=400",
      images: [
        "/placeholder.svg?height=600&width=400",
        "/placeholder.svg?height=600&width=400&text=2",
        "/placeholder.svg?height=600&width=400&text=3",
      ],
      isNew: false,
      isOnSale: true,
      category: "Платья",
      colors: ["Черный", "Белый", "Бежевый"],
      sizes: ["XS", "S", "M", "L", "XL"],
    },
    {
      id: 2,
      name: "БЛУЗА ИЗ НАТУРАЛЬНОГО ШЕЛКА",
      price: 4990,
      image: "/placeholder.svg?height=600&width=400",
      isNew: true,
      isOnSale: false,
      category: "Блузы",
    },
    {
      id: 3,
      name: "БРЮКИ С ВЫСОКОЙ ПОСАДКОЙ",
      price: 6490,
      image: "/placeholder.svg?height=600&width=400",
      isNew: false,
      isOnSale: false,
      category: "Брюки",
    },
    {
      id: 4,
      name: "ЮБКА МИДИ ПЛИССЕ",
      price: 5290,
      image: "/placeholder.svg?height=600&width=400",
      isNew: false,
      isOnSale: false,
      category: "Юбки",
    },
    {
      id: 5,
      name: "ЖАКЕТ ИЗ ИТАЛЬЯНСКОЙ ШЕРСТИ",
      price: 12900,
      salePrice: 9900,
      image: "/placeholder.svg?height=600&width=400",
      isNew: false,
      isOnSale: true,
      category: "Жакеты",
    },
    {
      id: 6,
      name: "ПЛАТЬЕ-РУБАШКА ИЗ ЛЬНА",
      price: 7990,
      image: "/placeholder.svg?height=600&width=400",
      isNew: true,
      isOnSale: false,
      category: "Платья",
    },
    {
      id: 7,
      name: "ТОПП С ДРАПИРОВКОЙ",
      price: 3990,
      image: "/placeholder.svg?height=600&width=400",
      isNew: false,
      isOnSale: false,
      category: "Топы",
    },
    {
      id: 8,
      name: "ПАЛЬТО ИЗ ШЕРСТИ",
      price: 18900,
      image: "/placeholder.svg?height=600&width=400",
      isNew: true,
      isOnSale: false,
      category: "Верхняя одежда",
    },
  ]

  // Категории
  const categories = [
    { id: "dresses", name: "Платья", count: 42 },
    { id: "blouses", name: "Блузы", count: 36 },
    { id: "pants", name: "Брюки", count: 28 },
    { id: "skirts", name: "Юбки", count: 24 },
    { id: "jackets", name: "Жакеты", count: 18 },
    { id: "accessories", name: "Аксессуары", count: 15 },
  ]

  // Цвета
  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"]

  // Функция для переключения фильтров
  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("")
  }

  // Компонент боковой панели фильтров
  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-none">
            <AccordionTrigger className="text-primary font-medium py-2 hover:no-underline">
              Категории
            </AccordionTrigger>
            <AccordionContent>
              <div className="space-y-2 pt-2">
                {categories.map((category) => (
                  <div key={category.id} className="flex items-center justify-between group">
                    <div className="flex items-center space-x-2">
                      <Checkbox 
                        id={`category-${category.id}`} 
                        checked={activeFilters.includes(category.id)}
                        onCheckedChange={() => toggleFilter(category.id)}
                        className="text-primary border-primary/30 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
                      />
                      <Label 
                        htmlFor={`category-${category.id}`}
                        className="text-sm cursor-pointer group-hover:text-primary transition-colors"
                      >
                        {category.name}
                      </Label>
                    </div>
                    <span className="text-xs text-gray-500">{category.count}</span>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* Цвета */}
      <div>
        <Accordion type="single" collapsible defaultValue="colors">
          <AccordionItem value="colors" className="border-none">
            <AccordionTrigger className="text-primary font-medium py-2 hover:no-underline">
              Цвета
            </AccordionTrigger>
            <AccordionContent>
              <div className="grid grid-cols-6 gap-2 pt-2">
                {colors.map((color) => (
                  <div key={color.id} className="flex flex-col items-center space-y-1">
                    <button
                      className={`w-8 h-8 rounded-full border ${
                        activeFilters.includes(color.id)
                          ? "ring-2 ring-primary ring-offset-2"
                          : "border-gray-200"
                      }`}
                      style={{ backgroundColor: color.hex }}
                      onClick={() => toggleFilter(color.id)}
                      aria-label={color.name}
                    />
                    <span className="text-xs text-gray-600">{color.name}</span>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* Размеры */}
      <div>
        <Accordion type="single" collapsible defaultValue="sizes">
          <AccordionItem value="sizes" className="border-none">
            <AccordionTrigger className="text-primary font-medium py-2 hover:no-underline">
              Размеры
            </AccordionTrigger>
            <AccordionContent>
              <div className="grid grid-cols-4 gap-2 pt-2">
                {sizes.map((size) => (
                  <button
                    key={size}
                    className={`border py-2 text-sm ${
                      activeFilters.includes(size)
                        ? "bg-primary text-white border-primary"
                        : "border-gray-200 hover:border-primary/50 text-gray-700"
                    }`}
                    onClick={() => toggleFilter(size)}
                  >
                    {size}
                  </button>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* Цена */}
      <div>
        <Accordion type="single" collapsible defaultValue="price">
          <AccordionItem value="price" className="border-none">
            <AccordionTrigger className="text-primary font-medium py-2 hover:no-underline">
              Цена
            </AccordionTrigger>
            <AccordionContent>
              <div className="pt-2 px-2">
                <Slider
                  defaultValue={priceRange}
                  max={15000}
                  step={100}
                  onValueChange={setPriceRange}
                  className="my-6"
                />
                <div className="flex items-center justify-between">
                  <div className="border border-gray-200 p-2 w-[45%] text-center text-sm">
                    {priceRange[0].toLocaleString()} ₽
                  </div>
                  <div className="border border-gray-200 p-2 w-[45%] text-center text-sm">
                    {priceRange[1].toLocaleString()} ₽
                  </div>
                </div>
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      </div>

      {/* Кнопки действий */}
      <div className="pt-4 space-y-3">
        <Button 
          className="w-full bg-primary hover:bg-primary/90 rounded-none"
          onClick={() => setIsFilterOpen(false)}
        >
          Применить фильтры
        </Button>
        <Button 
          variant="outline" 
          className="w-full border-primary/30 text-primary hover:bg-primary/5 rounded-none"
          onClick={clearAllFilters}
        >
          Сбросить все
        </Button>
      </div>
    </div>
  )

  return (
    <main className="pb-16">
      {/* Заголовок страницы */}
      <section 
        ref={heroRef}
        className="relative bg-tertiary/10 py-16 md:py-24 overflow-hidden"
      >
        <div className="absolute inset-0 pointer-events-none overflow-hidden">
          <div className="absolute top-0 left-0 w-full h-full opacity-5">
            <Image 
              src="/pattern.svg" 
              alt="" 
              fill 
              className="object-cover"
            />
          </div>
        </div>
        
        <div className="container mx-auto px-4 relative">
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={heroInView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.8 }}
            className="max-w-2xl mx-auto text-center"
          >
            <h1 className="text-3xl md:text-4xl lg:text-5xl font-light text-primary mb-4">Каталог</h1>
            <p className="text-gray-600 mb-6 max-w-xl mx-auto text-sm md:text-base">
              Откройте для себя нашу коллекцию элегантной одежды, созданной для современных женщин, 
              которые ценят качество, стиль и комфорт.
            </p>
            <div className="flex flex-wrap justify-center gap-3 md:gap-4">
              <Button 
                className="bg-primary hover:bg-primary/90 rounded-none min-w-[140px] md:min-w-[160px] text-sm md:text-base"
                asChild
              >
                <Link href="#products">
                  Смотреть все
                </Link>
              </Button>
              <Button 
                variant="outline" 
                className="border-primary/30 text-primary hover:bg-primary/5 rounded-none min-w-[140px] md:min-w-[160px] text-sm md:text-base"
                asChild
              >
                <Link href="/collections">
                  Коллекции
                  <ArrowUpRight className="ml-2 h-3 w-3 md:h-4 md:w-4" />
                </Link>
              </Button>
            </div>
          </motion.div>
        </div>
      </section>

      {/* Категории (только для мобильных) */}
      {isMobile && (
        <section className="py-6 overflow-hidden">
          <div className="container px-4 mx-auto">
            <h2 className="text-lg font-medium text-primary mb-4">Категории</h2>
            <div className="flex overflow-x-auto pb-4 gap-3 hide-scrollbar">
              {categories.map((category) => (
                <button
                  key={category.id}
                  className={`flex-shrink-0 px-4 py-2 border text-sm whitespace-nowrap ${
                    activeFilters.includes(category.id)
                      ? "bg-primary text-white border-primary"
                      : "border-gray-200 text-gray-700"
                  }`}
                  onClick={() => toggleFilter(category.id)}
                >
                  {category.name}
                </button>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Основной контент */}
      <section id="products" className="py-8 md:py-16">
        <div className="container mx-auto px-4">
          <div className="flex flex-col lg:flex-row gap-8">
            {/* Фильтры для десктопа */}
            <div className="hidden lg:block w-64 flex-shrink-0">
              <div className="sticky top-24">
                <FilterSidebar />
              </div>
            </div>

            {/* Фильтры для мобильных */}
            <div className="lg:hidden mb-6">
              <Sheet open={isFilterOpen} onOpenChange={setIsFilterOpen}>
                <SheetTrigger asChild>
                  <Button 
                    variant="outline" 
                    className="w-full border-primary/30 text-primary hover:bg-primary/5 rounded-none"
                  >
                    <Sliders className="mr-2 h-4 w-4" />
                    Фильтры и сортировка
                  </Button>
                </SheetTrigger>
                <SheetContent side="left" className="w-full sm:max-w-md overflow-auto">
                  <SheetHeader className="mb-6">
                    <SheetTitle className="text-primary">Фильтры</SheetTitle>
                    <SheetDescription>
                      Настройте параметры поиска для подбора идеальных товаров
                    </SheetDescription>
                  </SheetHeader>
                  <FilterSidebar />
                </SheetContent>
              </Sheet>
            </div>

            {/* Товары */}
            <div className="flex-1">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between mb-8 gap-4">
                <div>
                  <Select value={sortOption} onValueChange={setSortOption}>
                    <SelectTrigger className="w-full sm:w-[180px] border-primary/20 focus:ring-primary rounded-none">
                      <SelectValue placeholder="По популярности" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="popular">По популярности</SelectItem>
                      <SelectItem value="price-asc">По возрастанию цены</SelectItem>
                      <SelectItem value="price-desc">По убыванию цены</SelectItem>
                      <SelectItem value="new">Сначала новинки</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <div className="flex items-center gap-4">
                  <div className="hidden sm:block text-sm text-gray-500">
                    Показано: <span className="font-medium text-primary">{products.length}</span> из <span className="font-medium text-primary">120</span>
                  </div>
                  
                  <div className="flex border border-primary/20 rounded-none">
                    <button 
                      className={`p-2 ${viewMode === 'grid' ? 'bg-primary/10' : 'bg-white'}`}
                      onClick={() => setViewMode('grid')}
                      aria-label="Сетка"
                    >
                      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect x="1" y="1" width="6" height="6" stroke="#2B5F47" strokeWidth="1.5"/>
                        <rect x="9" y="1" width="6" height="6" stroke="#2B5F47" strokeWidth="1.5"/>
                        <rect x="1" y="9" width="6" height="6" stroke="#2B5F47" strokeWidth="1.5"/>
                        <rect x="9" y="9" width="6" height="6" stroke="#2B5F47" strokeWidth="1.5"/>
                      </svg>
                    </button>
                    <button 
                      className={`p-2 ${viewMode === 'list' ? 'bg-primary/10' : 'bg-white'} ${isMobile ? 'hidden' : 'block'}`}
                      onClick={() => setViewMode('list')}
                      aria-label="Список"
                      disabled={isMobile}
                    >
                      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect x="1" y="1" width="14" height="3" stroke="#2B5F47" strokeWidth="1.5"/>
                        <rect x="1" y="6" width="14" height="3" stroke="#2B5F47" strokeWidth="1.5"/>
                        <rect x="1" y="11" width="14" height="3" stroke="#2B5F47" strokeWidth="1.5"/>
                      </svg>
                    </button>
                  </div>
                </div>
              </div>

              {/* Активные фильтры */}
              {activeFilters.length > 0 && (
                <div className="flex flex-wrap gap-2 mb-6">
                  {activeFilters.map(filter => {
                    // Найдем название фильтра для отображения
                    let filterName = filter;
                    const category = categories.find(c => c.id === filter);
                    const color = colors.find(c => c.id === filter);
                    
                    if (category) filterName = category.name;
                    if (color) filterName = color.name;
                    
                    return (
                      <div 
                        key={filter}
                        className="flex items-center bg-primary/5 px-3 py-1 text-sm text-primary border border-primary/10"
                      >
                        <span>{filterName}</span>
                        <button 
                          onClick={() => toggleFilter(filter)}
                          className="ml-2 text-primary/70 hover:text-primary"
                        >
                          <X className="h-3 w-3" />
                        </button>
                      </div>
                    );
                  })}
                  <button 
                    className="text-sm text-primary/70 hover:text-primary underline"
                    onClick={clearAllFilters}
                  >
                    Очистить все
                  </button>
                </div>
              )}

              {/* Сетка товаров */}
              <div className="mb-12">
                {viewMode === 'grid' ? (
                  <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-3 gap-3 md:gap-6">
                    {products.map(product => (
                      <ProductCard
                        key={product.id}
                        id={product.id}
                        name={product.name}
                        price={product.price}
                        salePrice={product.salePrice}
                        image={product.image}
                        isNew={product.isNew}
                        isOnSale={product.isOnSale}
                        category={product.category}
                      />
                    ))}
                  </div>
                ) : (
                  <div className="space-y-6">
                    {products.map(product => (
                      <div 
                        key={product.id}
                        className="flex flex-col sm:flex-row border border-gray-100 hover:border-primary/20 transition-colors"
                      >
                        <div className="w-full sm:w-1/3 relative">
                          <Link href={`/product/${product.id}`} className="block h-full">
                            <Image 
                              src={product.image} 
                              alt={product.name}
                              width={400}
                              height={600}
                              className="w-full h-full object-cover"
                            />
                          </Link>
                          {product.isNew && (
                            <div className="absolute top-2 right-2 bg-primary text-white text-xs py-1 px-2">
                              НОВИНКА
                            </div>
                          )}
                          {product.isOnSale && (
                            <div className="absolute top-2 left-2 bg-[#E2725B] text-white text-xs py-1 px-2">
                              СКИДКА
                            </div>
                          )}
                        </div>
                        <div className="w-full sm:w-2/3 p-4 sm:pl-6 sm:pr-4 sm:py-4 flex flex-col">
                          <div className="text-xs text-gray-500 mb-1">{product.category}</div>
                          <h3 className="text-primary font-medium mb-2">{product.name}</h3>
                          <div className="flex items-center gap-2 mb-4">
                            {product.isOnSale && product.salePrice ? (
                              <>
                                <p className="text-lg font-medium text-secondary">{product.salePrice.toLocaleString()} ₽</p>
                                <p className="text-sm text-gray-500 line-through">{product.price.toLocaleString()} ₽</p>
                              </>
                            ) : (
                              <p className="text-lg font-medium text-secondary">{product.price.toLocaleString()} ₽</p>
                            )}
                          </div>
                          
                          {/* Доступные цвета */}
                          <div className="mb-4">
                            <div className="text-sm text-gray-600 mb-2">Доступные цвета:</div>
                            <div className="flex gap-2">
                              {(product.colors || ["Черный"]).map((color, idx) => (
                                <button
                                  key={idx}
                                  className={`w-6 h-6 rounded-full border ${
                                    selectedImage === idx ? "ring-2 ring-primary ring-offset-1" : "border-gray-200"
                                  }`}
                                  style={{ 
                                    backgroundColor: 
                                      color === "Черный" ? "#000" : 
                                      color === "Белый" ? "#fff" : 
                                      color === "Бежевый" ? "#F5F5DC" : "#ddd" 
                                  }}
                                  onClick={() => setSelectedImage(idx)}
                                  aria-label={color}
                                />
                              ))}
                            </div>
                          </div>
                          
                          <div className="mt-auto flex flex-wrap gap-2">
                            <Button 
                              className="bg-primary hover:bg-primary/90 text-white rounded-none"
                            >
                              В корзину
                            </Button>
                            <Button 
                              variant="outline" 
                              className="border-primary/30 text-primary hover:bg-primary/5 rounded-none"
                              asChild
                            >
                              <Link href={`/product/${product.id}`}>
                                Подробнее
                              </Link>
                            </Button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* Пагинация */}
              <div className="mt-12 flex justify-center">
                <nav className="flex items-center gap-1">
                  <Button 
                    variant="outline" 
                    size="icon" 
                    className="border-primary/20 text-primary hover:bg-primary/5 w-9 h-9 rounded-none"
                    disabled={currentPage === 1}
                    onClick={() => setCurrentPage(currentPage - 1)}
                  >
                    <ChevronUp className="h-4 w-4 rotate-90" />
                  </Button>
                  
                  {[1, 2, 3, 4, 5].map(page => (
                    <Button 
                      key={page}
                      variant={currentPage === page ? "default" : "outline"}
                      className={currentPage === page 
                        ? "bg-primary hover:bg-primary/90 text-white w-9 h-9 rounded-none" 
                        : "border-primary/20 text-primary hover:bg-primary/5 w-9 h-9 rounded-none"
                      }
                      onClick={() => setCurrentPage(page)}
                    >
                      {page}
                    </Button>
                  ))}
                  
                  <Button 
                    variant="outline" 
                    size="icon" 
                    className="border-primary/20 text-primary hover:bg-primary/5 w-9 h-9 rounded-none"
                    disabled={currentPage === 5}
                    onClick={() => setCurrentPage(currentPage + 1)}
                  >
                    <ChevronDown className="h-4 w-4 rotate-90" />
                  </Button>
                </nav>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Стили для скрытия полосы прокрутки */}
      <style jsx global>{`
        .hide-scrollbar::-webkit-scrollbar {
          display: none;
        }
        .hide-scrollbar {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
      `}</style>
    </main>
  )
}
