"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { 
  ShoppingBag, 
  Heart, 
  Share2, 
  Star, 
  Truck, 
  RefreshCw, 
  Check, 
  ChevronRight, 
  Minus, 
  Plus,
  ArrowRight
} from "lucide-react"
import { motion } from "framer-motion"
import { ProductCard } from "@/components/ui/product-card"

export default function ProductPage({ params }: { params: { id: string } }) {
  const [selectedSize, setSelectedSize] = useState("")
  const [selectedColor, setSelectedColor] = useState("")
  const [quantity, setQuantity] = useState(1)
  const [activeTab, setActiveTab] = useState("description")
  const [activeImage, setActiveImage] = useState(0)
  const [isZoomed, setIsZoomed] = useState(false)
  const [zoomPosition, setZoomPosition] = useState({ x: 0, y: 0 })


  const incrementQuantity = () => {
    setQuantity(quantity + 1)
  }

  const decrementQuantity = () => {
    if (quantity > 1) {
      setQuantity(quantity - 1)
    }
  }

  const handleImageHover = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!isZoomed) return
    
    const { left, top, width, height } = e.currentTarget.getBoundingClientRect()
    const x = ((e.clientX - left) / width) * 100
    const y = ((e.clientY - top) / height) * 100
    
    setZoomPosition({ x, y })
  }

  return (
    <main className="pb-20">
      {/* Хлебные крошки */}
      <div className="bg-tertiary/10 py-4">
        <div className="container mx-auto px-4">
          <nav className="flex text-sm text-gray-500">
            <Link href="/" className="hover:text-primary transition-colors">
              Главная
            </Link>
            <ChevronRight className="h-4 w-4 mx-2 mt-0.5" />
            <Link href="/catalog" className="hover:text-primary transition-colors">
              Каталог
            </Link>
            <ChevronRight className="h-4 w-4 mx-2 mt-0.5" />
            <Link href={`/catalog?category=${product.category.toLowerCase()}`} className="hover:text-primary transition-colors">
              {product.category}
            </Link>
            <ChevronRight className="h-4 w-4 mx-2 mt-0.5" />
            <span className="text-primary">{product.name}</span>
          </nav>
        </div>
      </div>

      {/* Информация о продукте */}
      <section className="py-10">
        <div className="container mx-auto px-4">
          <div className="flex flex-col lg:flex-row gap-10">
            {/* Галерея изображений */}
            <div className="w-full lg:w-3/5">
              <div className="flex flex-col-reverse md:flex-row gap-4">
                {/* Миниатюры */}
                <div className="flex md:flex-col gap-2 mt-4 md:mt-0">
                  {product.images.map((image, index) => (
                    <button
                      key={index}
                      className={`relative w-16 h-20 border-2 transition-colors ${
                        activeImage === index ? "border-primary" : "border-transparent hover:border-primary/30"
                      }`}
                      onClick={() => setActiveImage(index)}
                    >
                      <Image src={image} alt={`${product.name} - изображение ${index + 1}`} fill className="object-cover" />
                    </button>
                  ))}
                </div>
                
                {/* Основное изображение */}
                <div 
                  className="relative flex-1 aspect-[3/4] overflow-hidden bg-tertiary/5"
                  onMouseEnter={() => setIsZoomed(true)}
                  onMouseLeave={() => setIsZoomed(false)}
                  onMouseMove={handleImageHover}
                >
                  <div 
                    className="absolute inset-0 transition-transform duration-200"
                    style={{ 
                      backgroundImage: `url(${product.images[activeImage]})`,
                      backgroundPosition: isZoomed ? `${zoomPosition.x}% ${zoomPosition.y}%` : 'center',
                      backgroundSize: isZoomed ? '150%' : 'cover',
                      backgroundRepeat: 'no-repeat'
                    }}
                  />
                  
                  {product.discount > 0 && (
                    <div className="absolute top-4 left-4 bg-secondary text-white text-sm py-1 px-3 z-10">
                      -{product.discount}%
                    </div>
                  )}
                </div>
              </div>
            </div>
            
            {/* Информация о товаре */}
            <div className="w-full lg:w-2/5">
              <div className="sticky top-24">
                <div className="text-sm text-gray-500 mb-2">{product.category}</div>
                <h1 className="text-2xl md:text-3xl font-medium text-primary mb-4">{product.name}</h1>
                
                {/* Рейтинг */}
                <div className="flex items-center mb-6">
                  <div className="flex">
                    {[1, 2, 3, 4, 5].map((star) => (
                      <Star
                        key={star}
                        className={`h-4 w-4 ${
                          star <= Math.floor(product.rating) ? "text-secondary fill-secondary" : "text-gray-300"
                        }`}
                      />
                    ))}
                  </div>
                  <span className="ml-2 text-sm text-gray-500">
                    {product.rating} ({product.reviewCount} отзывов)
                  </span>
                </div>
                
                {/* Цена */}
                <div className="flex items-center gap-3 mb-8">
                  {product.oldPrice ? (
                    <>
                      <span className="text-2xl font-medium text-secondary">{product.price.toLocaleString()} ₽</span>
                      <span className="text-lg text-gray-500 line-through">{product.oldPrice.toLocaleString()} ₽</span>
                    </>
                  ) : (
                    <span className="text-2xl font-medium text-secondary">{product.price.toLocaleString()} ₽</span>
                  )}
                </div>
                
                {/* Артикул и наличие */}
                <div className="flex justify-between text-sm text-gray-500 mb-8">
                  <span>Артикул: {product.sku}</span>
                  <span className="flex items-center">
                    {product.inStock ? (
                      <>
                        <Check className="h-4 w-4 text-green-500 mr-1" />
                        В наличии
                      </>
                    ) : (
                      "Нет в наличии"
                    )}
                  </span>
                </div>
                
                {/* Выбор цвета */}
                <div className="mb-6">
                  <div className="flex justify-between mb-3">
                    <span className="text-sm font-medium">Цвет</span>
                    <span className="text-sm text-gray-500">{selectedColor || "Выберите цвет"}</span>
                  </div>
                  <div className="flex gap-3">
                    {product.colors.map((color) => (
                      <button
                        key={color.name}
                        className={`w-10 h-10 rounded-full transition-all ${
                          color.border ? "border border-gray-300" : ""
                        } ${
                          selectedColor === color.name
                            ? "ring-2 ring-primary ring-offset-2"
                            : "hover:ring-1 hover:ring-primary/50 hover:ring-offset-1"
                        }`}
                        style={{ backgroundColor: color.code }}
                        onClick={() => setSelectedColor(color.name)}
                        aria-label={`Цвет: ${color.name}`}
                      />
                    ))}
                  </div>
                </div>
                
                {/* Выбор размера */}
                <div className="mb-8">
                  <div className="flex justify-between mb-3">
                    <span className="text-sm font-medium">Размер</span>
                    <Link href="/size-guide" className="text-sm text-primary hover:underline">
                      Таблица размеров
                    </Link>
                  </div>
                  <div className="grid grid-cols-5 gap-2">
                    {product.sizes.map((size) => (
                      <button
                        key={size}
                        className={`h-12 flex items-center justify-center border transition-colors ${
                          selectedSize === size
                            ? "bg-primary text-white border-primary"
                            : "border-gray-300 hover:border-primary/50"
                        }`}
                        onClick={() => setSelectedSize(size)}
                      >
                        {size}
                      </button>
                    ))}
                  </div>
                </div>
                
                {/* Количество */}
                <div className="mb-8">
                  <div className="flex justify-between mb-3">
                    <span className="text-sm font-medium">Количество</span>
                  </div>
                  <div className="flex">
                    <button
                      className="w-12 h-12 border border-gray-300 flex items-center justify-center hover:bg-gray-50"
                      onClick={decrementQuantity}
                    >
                      <Minus className="h-4 w-4" />
                    </button>
                    <div className="w-16 h-12 border-t border-b border-gray-300 flex items-center justify-center">
                      {quantity}
                    </div>
                    <button
                      className="w-12 h-12 border border-gray-300 flex items-center justify-center hover:bg-gray-50"
                      onClick={incrementQuantity}
                    >
                      <Plus className="h-4 w-4" />
                    </button>
                  </div>
                </div>
                
                {/* Кнопки действий */}
                <div className="flex flex-col gap-3 mb-8">
                  <Button className="bg-primary hover:bg-primary/90 h-12 text-base">
                    <ShoppingBag className="h-5 w-5 mr-2" />
                    Добавить в корзину
                  </Button>
                  <div className="grid grid-cols-2 gap-3">
                    <Button variant="outline" className="border-primary/30 text-primary hover:bg-primary/5 h-12">
                      <Heart className="h-5 w-5 mr-2" />
                      В избранное
                    </Button>
                    <Button variant="outline" className="border-primary/30 text-primary hover:bg-primary/5 h-12">
                      <Share2 className="h-5 w-5 mr-2" />
                      Поделиться
                    </Button>
                  </div>
                </div>
                
                {/* Доставка и возврат */}
                <div className="space-y-4 border-t border-gray-200 pt-6">
                  <div className="flex items-start">
                    <Truck className="h-5 w-5 text-primary mr-3 mt-0.5" />
                    <div>
                      <h3 className="text-sm font-medium mb-1">Доставка</h3>
                      <p className="text-sm text-gray-500">{product.delivery}</p>
                    </div>
                  </div>
                  <div className="flex items-start">
                    <RefreshCw className="h-5 w-5 text-primary mr-3 mt-0.5" />
                    <div>
                      <h3 className="text-sm font-medium mb-1">Возврат</h3>
                      <p className="text-sm text-gray-500">{product.returns}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Информация о товаре в табах */}
      <section className="py-10 bg-tertiary/10">
        <div className="container mx-auto px-4">
          <Tabs defaultValue="description" className="w-full">
            <TabsList className="w-full max-w-2xl mx-auto grid grid-cols-3 mb-8 bg-transparent">
              <TabsTrigger 
                value="description" 
                className={`text-sm py-3 border-b-2 rounded-none data-[state=active]:border-primary data-[state=active]:text-primary data-[state=active]:shadow-none ${
                  activeTab === "description" ? "border-primary text-primary" : "border-transparent text-gray-500"
                }`}
                onClick={() => setActiveTab("description")}
              >
                Описание
              </TabsTrigger>
              <TabsTrigger 
                value="details" 
                className={`text-sm py-3 border-b-2 rounded-none data-[state=active]:border-primary data-[state=active]:text-primary data-[state=active]:shadow-none ${
                  activeTab === "details" ? "border-primary text-primary" : "border-transparent text-gray-500"
                }`}
                onClick={() => setActiveTab("details")}
              >
                Детали
              </TabsTrigger>
              <TabsTrigger 
                value="care" 
                className={`text-sm py-3 border-b-2 rounded-none data-[state=active]:border-primary data-[state=active]:text-primary data-[state=active]:shadow-none ${
                  activeTab === "care" ? "border-primary text-primary" : "border-transparent text-gray-500"
                }`}
                onClick={() => setActiveTab("care")}
              >
                Уход
              </TabsTrigger>
            </TabsList>
            
            <div className="max-w-3xl mx-auto">
              <TabsContent value="description" className="mt-0">
                <div className="bg-white p-8 shadow-sm">
                  <p className="text-gray-700 leading-relaxed">{product.description}</p>
                </div>
              </TabsContent>
              
              <TabsContent value="details" className="mt-0">
                <div className="bg-white p-8 shadow-sm">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <h3 className="text-sm font-medium mb-4">Характеристики</h3>
                      <ul className="space-y-3">
                        {product.details.map((detail, index) => (
                          <li key={index} className="flex items-center text-gray-700">
                            <Check className="h-4 w-4 text-primary mr-2" />
                            {detail}
                          </li>
                        ))}
                      </ul>
                    </div>
                    <div>
                      <h3 className="text-sm font-medium mb-4">Состав</h3>
                      <p className="text-gray-700">{product.composition}</p>
                    </div>
                  </div>
                </div>
              </TabsContent>
              
              <TabsContent value="care" className="mt-0">
                <div className="bg-white p-8 shadow-sm">
                  <h3 className="text-sm font-medium mb-4">Рекомендации по уходу</h3>
                  <p className="text-gray-700 leading-relaxed mb-6">{product.care}</p>
                  <div className="flex flex-wrap gap-4">
                    <div className="flex items-center justify-center w-16 h-16 border border-gray-200">
                      <Image src="/placeholder.svg?height=40&width=40&text=30°" alt="Стирка при 30°C" width={40} height={40} />
                    </div>
                    <div className="flex items-center justify-center w-16 h-16 border border-gray-200">
                      <Image src="/placeholder.svg?height=40&width=40&text=No Bleach" alt="Не отбеливать" width={40} height={40} />
                    </div>
                    <div className="flex items-center justify-center w-16 h-16 border border-gray-200">
                      <Image src="/placeholder.svg?height=40&width=40&text=Iron Low" alt="Гладить при низкой температуре" width={40} height={40} />
                    </div>
                    <div className="flex items-center justify-center w-16 h-16 border border-gray-200">
                      <Image src="/placeholder.svg?height=40&width=40&text=No Dry Clean" alt="Не подвергать химической чистке" width={40} height={40} />
                    </div>
                  </div>
                </div>
              </TabsContent>
            </div>
          </Tabs>
        </div>
      </section>

      {/* Рекомендуемые товары */}
      <section className="py-16">
        <div className="container mx-auto px-4">
          <div className="flex flex-col md:flex-row justify-between items-center mb-10">
            <h2 className="text-2xl md:text-3xl font-serif text-primary mb-4 md:mb-0">С ЭТИМ ТОВАРОМ ПОКУПАЮТ</h2>
            <Button 
              asChild
              variant="outline" 
              className="border-primary/30 text-primary hover:bg-primary/5 group"
            >
              <Link href="/catalog">
                СМОТРЕТЬ ВСЕ
                <ArrowRight className="ml-2 h-4 w-4 transition-transform group-hover:translate-x-1" />
              </Link>
            </Button>
          </div>
          
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {recommendedProducts.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>
      </section>
    </main>
  )
}

