"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Trash2, Plus, Minus, ArrowRight, ShoppingBag, Heart, ChevronLeft, Clock, ShieldCheck, Truck } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import { motion, AnimatePresence } from "framer-motion"
import { useInView } from "react-intersection-observer"

interface CartItem {
  id: number
  name: string
  price: number
  quantity: number
  size: string
  color: string
  image: string
}

export default function CartPage() {
  // Mock cart items
  const [cartItems, setCartItems] = useState<CartItem[]>([
    {
      id: 1,
      name: "ПЛАТЬЕ С ЦВЕТОЧНЫМ ПРИНТОМ",
      price: 5990,
      quantity: 1,
      size: "M",
      color: "Белый",
      image: "/placeholder.svg?height=600&width=400",
    },
    {
      id: 2,
      name: "БЛУЗА ИЗ НАТУРАЛЬНОГО ШЕЛКА",
      price: 4990,
      quantity: 2,
      size: "S",
      color: "Синий",
      image: "/placeholder.svg?height=600&width=400",
    },
  ])
  const [promoCode, setPromoCode] = useState("")
  const [promoApplied, setPromoApplied] = useState(false)
  const [ref1, inView1] = useInView({ triggerOnce: true, threshold: 0.1 })
  const [ref2, inView2] = useInView({ triggerOnce: true, threshold: 0.1 })
  const [ref3, inView3] = useInView({ triggerOnce: true, threshold: 0.1 })

  const updateQuantity = (id: number, newQuantity: number) => {
    if (newQuantity < 1) return

    setCartItems(cartItems.map((item) => (item.id === id ? { ...item, quantity: newQuantity } : item)))
  }

  const removeItem = (id: number) => {
    setCartItems(cartItems.filter((item) => item.id !== id))
  }

  const moveToWishlist = (id: number) => {
    // В реальном приложении здесь был бы код для добавления в избранное
    console.log(`Товар ${id} добавлен в избранное`)
    removeItem(id)
  }

  const applyPromoCode = () => {
    if (promoCode.trim() === "SALE20") {
      setPromoApplied(true)
    } else {
      alert("Неверный промокод")
    }
  }

  // Calculate totals
  const subtotal = cartItems.reduce((total, item) => total + item.price * item.quantity, 0)
  const shipping = subtotal >= 5000 ? 0 : 500 // Free shipping for orders over 5000
  const discount = promoApplied ? Math.round(subtotal * 0.2) : 0 // 20% discount if promo applied
  const total = subtotal + shipping - discount

  // Recommended products
  const recommendedProducts = [
    {
      id: 3,
      name: "ЮБКА МИДИ ПЛИССЕ",
      price: 5290,
      image: "/placeholder.svg?height=600&width=400",
    },
    {
      id: 4,
      name: "ЖАКЕТ ИЗ ИТАЛЬЯНСКОЙ ШЕРСТИ",
      price: 12900,
      image: "/placeholder.svg?height=600&width=400",
    },
    {
      id: 5,
      name: "ПЛАТЬЕ-РУБАШКА ИЗ ЛЬНА",
      price: 7990,
      image: "/placeholder.svg?height=600&width=400",
    },
  ]

  // Анимационные варианты
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: { 
      opacity: 1,
      transition: { 
        staggerChildren: 0.1
      }
    }
  }
  
  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0, transition: { duration: 0.5 } }
  }

  return (
    <div className="bg-white min-h-screen">
      <div className="container mx-auto px-4 py-8 md:py-16">
        <div className="flex items-center mb-8 md:mb-12">
          <Link href="/catalog" className="text-primary hover:text-primary/80 flex items-center text-sm md:text-base transition-colors duration-200">
            <ChevronLeft className="h-4 w-4 mr-1" />
            Вернуться к покупкам
          </Link>
        </div>
        
        <h1 className="text-2xl md:text-3xl lg:text-4xl font-light text-primary mb-8 md:mb-12 tracking-tight">Корзина</h1>

        <AnimatePresence mode="wait">
          {cartItems.length === 0 ? (
            <motion.div 
              key="empty-cart"
              initial={{ opacity: 0 }} 
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.5 }}
              className="text-center py-16 md:py-24 max-w-2xl mx-auto"
            >
              <div className="inline-flex items-center justify-center w-24 h-24 md:w-32 md:h-32 bg-tertiary/20 rounded-full mb-8">
                <ShoppingBag className="h-12 w-12 md:h-16 md:w-16 text-primary" />
              </div>
              <h2 className="text-xl md:text-2xl font-medium text-primary mb-4">Ваша корзина пуста</h2>
              <p className="text-gray-600 mb-10 max-w-md mx-auto text-base md:text-lg">
                Добавьте товары в корзину, чтобы оформить заказ. Вы можете найти множество интересных товаров в нашем
                каталоге.
              </p>
              <Button 
                className="bg-primary hover:bg-primary/90 text-white rounded-none min-w-[220px] py-6"
                asChild
              >
                <Link href="/catalog">
                  Перейти в каталог
                  <ArrowRight className="ml-2 h-4 w-4" />
                </Link>
              </Button>
            </motion.div>
          ) : (
            <div className="grid md:grid-cols-3 gap-8 md:gap-12">
              {/* Cart Items */}
              <motion.div 
                ref={ref1}
                variants={containerVariants}
                initial="hidden"
                animate={inView1 ? "visible" : "hidden"}
                className="md:col-span-2 space-y-6 md:space-y-8"
              >
                {cartItems.map((item, index) => (
                  <motion.div
                    key={item.id}
                    variants={itemVariants}
                    className="flex flex-col sm:flex-row gap-6 p-6 border border-gray-100 hover:border-primary/20 transition-all duration-300 bg-white shadow-sm hover:shadow-md"
                  >
                    <div className="relative w-full sm:w-32 md:w-40 h-48 sm:h-40 flex-shrink-0 overflow-hidden">
                      <Link href={`/product/${item.id}`}>
                        <Image 
                          src={item.image || "/placeholder.svg"} 
                          alt={item.name} 
                          fill 
                          className="object-cover transition-transform duration-700 hover:scale-105" 
                        />
                      </Link>
                    </div>

                    <div className="flex-1 flex flex-col">
                      <div className="flex justify-between">
                        <Link
                          href={`/product/${item.id}`}
                          className="text-base md:text-lg font-medium text-primary hover:text-secondary transition-colors duration-200"
                        >
                          {item.name}
                        </Link>
                        <button
                          onClick={() => removeItem(item.id)}
                          className="text-gray-400 hover:text-primary transition-colors duration-200"
                          aria-label="Удалить товар"
                        >
                          <Trash2 className="h-5 w-5" />
                        </button>
                      </div>

                      <div className="mt-2 text-sm text-gray-500 space-y-1">
                        <div><span className="text-gray-600">Размер:</span> {item.size}</div>
                        <div><span className="text-gray-600">Цвет:</span> {item.color}</div>
                      </div>

                      <div className="mt-auto pt-6 flex flex-wrap items-center justify-between gap-4">
                        <div className="flex items-center border border-gray-200 bg-white">
                          <button
                            onClick={() => updateQuantity(item.id, item.quantity - 1)}
                            className="w-10 h-10 flex items-center justify-center text-gray-500 hover:text-primary transition-colors"
                            aria-label="Уменьшить количество"
                          >
                            <Minus className="h-4 w-4" />
                          </button>
                          <span className="w-12 text-center font-medium">{item.quantity}</span>
                          <button
                            onClick={() => updateQuantity(item.id, item.quantity + 1)}
                            className="w-10 h-10 flex items-center justify-center text-gray-500 hover:text-primary transition-colors"
                            aria-label="Увеличить количество"
                          >
                            <Plus className="h-4 w-4" />
                          </button>
                        </div>

                        <div className="flex items-center gap-6">
                          <button
                            onClick={() => moveToWishlist(item.id)}
                            className="text-gray-500 hover:text-primary transition-colors duration-200 flex items-center text-sm"
                          >
                            <Heart className="h-4 w-4 mr-2" />
                            <span className="hidden sm:inline">В избранное</span>
                          </button>
                          <div className="text-lg font-medium text-primary">
                            {(item.price * item.quantity).toLocaleString()} ₽
                          </div>
                        </div>
                      </div>
                    </div>
                  </motion.div>
                ))}

                {/* Promo Code */}
                <motion.div 
                  variants={itemVariants}
                  className="mt-8 p-6 border border-gray-100 bg-tertiary/5 shadow-sm"
                >
                  <h3 className="text-lg font-medium text-primary mb-4">Промокод</h3>
                  <div className="flex gap-2">
                    <Input
                      type="text"
                      placeholder="Введите промокод"
                      value={promoCode}
                      onChange={(e) => setPromoCode(e.target.value)}
                      className="border-gray-200 focus:border-primary focus:ring-primary rounded-none"
                      disabled={promoApplied}
                    />
                    <Button
                      onClick={applyPromoCode}
                      className={`rounded-none ${
                        promoApplied
                          ? "bg-green-600 hover:bg-green-700"
                          : "bg-primary hover:bg-primary/90"
                      } text-white transition-colors duration-200`}
                      disabled={promoApplied || !promoCode.trim()}
                    >
                      {promoApplied ? "Применен" : "Применить"}
                    </Button>
                  </div>
                  <AnimatePresence>
                    {promoApplied && (
                      <motion.p 
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: 'auto' }}
                        exit={{ opacity: 0, height: 0 }}
                        className="mt-3 text-sm text-green-600 flex items-center"
                      >
                        <svg className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                        Промокод успешно применен! Скидка 20%
                      </motion.p>
                    )}
                  </AnimatePresence>
                </motion.div>
              </motion.div>

              {/* Order Summary */}
              <motion.div 
                ref={ref2}
                initial={{ opacity: 0, y: 20 }}
                animate={inView2 ? { opacity: 1, y: 0 } : {}}
                transition={{ duration: 0.8, delay: 0.3 }}
                className="md:sticky md:top-24 h-fit"
              >
                <div className="border border-gray-100 p-6 bg-white shadow-sm">
                  <h2 className="text-xl font-medium text-primary mb-6">Ваш заказ</h2>

                  <div className="space-y-4 text-base">
                    <div className="flex justify-between">
                      <span className="text-gray-600">Товары ({cartItems.length}):</span>
                      <span>{subtotal.toLocaleString()} ₽</span>
                    </div>

                    <div className="flex justify-between">
                      <span className="text-gray-600">Доставка:</span>
                      <span>{shipping === 0 ? "Бесплатно" : `${shipping.toLocaleString()} ₽`}</span>
                    </div>

                    <AnimatePresence>
                      {promoApplied && (
                        <motion.div 
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: 'auto' }}
                          exit={{ opacity: 0, height: 0 }}
                          className="flex justify-between text-green-600"
                        >
                          <span>Скидка (20%):</span>
                          <span>-{discount.toLocaleString()} ₽</span>
                        </motion.div>
                      )}
                    </AnimatePresence>

                    <Separator className="my-4" />

                    <div className="flex justify-between font-medium text-lg">
                      <span>Итого:</span>
                      <span className="text-primary">{total.toLocaleString()} ₽</span>
                    </div>
                  </div>

                  <Button
                    className="w-full mt-8 bg-primary hover:bg-primary/90 text-white rounded-none py-6 transition-colors duration-200"
                    asChild
                  >
                    <Link href="/checkout">
                      Оформить заказ
                      <ArrowRight className="ml-2 h-4 w-4" />
                    </Link>
                  </Button>

                  <div className="mt-4 text-xs text-gray-500 text-center">
                    Нажимая кнопку "Оформить заказ", вы соглашаетесь с условиями <Link href="/terms" className="underline hover:text-primary transition-colors duration-200">пользовательского соглашения</Link> и <Link href="/privacy" className="underline hover:text-primary transition-colors duration-200">политикой конфиденциальности</Link>.
                  </div>
                </div>

                <div className="mt-6 p-6 border border-gray-100 bg-tertiary/5 shadow-sm">
                  <div className="space-y-4">
                    <div className="flex items-center gap-3">
                      <Truck className="h-5 w-5 text-primary flex-shrink-0" />
                      <span className="text-sm">Бесплатная доставка от 5000 ₽</span>
                    </div>
                    <div className="flex items-center gap-3">
                      <Clock className="h-5 w-5 text-primary flex-shrink-0" />
                      <span className="text-sm">Возврат в течение 14 дней</span>
                    </div>
                    <div className="flex items-center gap-3">
                      <ShieldCheck className="h-5 w-5 text-primary flex-shrink-0" />
                      <span className="text-sm">Безопасная оплата</span>
                    </div>
                  </div>
                </div>
              </motion.div>
            </div>
          )}
        </AnimatePresence>

        {/* Recommended Products */}
        {cartItems.length > 0 && (
          <motion.div 
            ref={ref3}
            initial={{ opacity: 0, y: 30 }}
            animate={inView3 ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.8 }}
            className="mt-16 md:mt-24"
          >
            <h2 className="text-xl md:text-2xl font-light text-primary mb-8 tracking-tight">Вам также может понравиться</h2>
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6">
              {recommendedProducts.map((product, index) => (
                <motion.div 
                  key={product.id} 
                  initial={{ opacity: 0, y: 20 }}
                  animate={inView3 ? { opacity: 1, y: 0 } : {}}
                  transition={{ duration: 0.5, delay: index * 0.1 }}
                  className="border border-gray-100 hover:border-primary/20 transition-all duration-300 group bg-white shadow-sm hover:shadow-md"
                >
                  <Link href={`/product/${product.id}`} className="block">
                    <div className="relative aspect-[3/4] overflow-hidden">
                      <Image
                        src={product.image}
                        alt={product.name}
                        fill
                        className="object-cover transition-transform duration-700 group-hover:scale-105"
                      />
                    </div>
                    <div className="p-4 md:p-6">
                      <h3 className="text-sm md:text-base font-medium text-primary line-clamp-2 mb-2 group-hover:text-secondary transition-colors duration-200">{product.name}</h3>
                      <p className="text-base md:text-lg font-medium text-primary">{product.price.toLocaleString()} ₽</p>
                    </div>
                  </Link>
                </motion.div>
              ))}
            </div>
          </motion.div>
        )}
      </div>
    </div>
  )
}

