"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Separator } from "@/components/ui/separator"
import { Textarea } from "@/components/ui/textarea"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"
import { motion, AnimatePresence } from "framer-motion"
import { useInView } from "react-intersection-observer"
import { ChevronLeft, CreditCard, Truck, Check, ShieldCheck, Clock } from "lucide-react"

export default function CheckoutPage() {
  const [step, setStep] = useState(1)
  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    address: "",
    city: "",
    postalCode: "",
    deliveryMethod: "courier",
    paymentMethod: "card",
    comment: ""
  })
  const [orderComplete, setOrderComplete] = useState(false)
  const [ref1, inView1] = useInView({ triggerOnce: true, threshold: 0.1 })
  const [ref2, inView2] = useInView({ triggerOnce: true, threshold: 0.1 })

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { id, value } = e.target
    setFormData(prev => ({ ...prev, [id]: value }))
  }

  const handleRadioChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    // В реальном приложении здесь был бы код для отправки заказа
    console.log("Заказ оформлен:", formData)
    setOrderComplete(true)
  }

  // Mock cart items
  const cartItems = [
    {
      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",
    },
  ]

  // Calculate totals
  const subtotal = cartItems.reduce((total, item) => total + item.price * item.quantity, 0)
  const shipping = formData.deliveryMethod === "courier" ? 500 : formData.deliveryMethod === "pickup" ? 300 : 400
  const total = subtotal + shipping

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

  const staggerContainer = {
    hidden: { opacity: 0 },
    visible: { 
      opacity: 1,
      transition: { 
        staggerChildren: 0.1
      }
    }
  }

  if (orderComplete) {
    return (
      <motion.div 
        initial={{ opacity: 0 }} 
        animate={{ opacity: 1 }} 
        className="container mx-auto px-4 py-16 md:py-24 text-center max-w-2xl"
      >
        <div className="inline-flex items-center justify-center w-24 h-24 md:w-32 md:h-32 bg-primary/10 rounded-full mb-8">
          <Check className="h-12 w-12 md:h-16 md:w-16 text-primary" />
        </div>
        <h1 className="text-2xl md:text-3xl lg:text-4xl font-light text-primary mb-6 tracking-tight">Заказ успешно оформлен</h1>
        <p className="text-gray-600 mb-8 text-base md:text-lg">
          Спасибо за ваш заказ! Мы отправили подтверждение на вашу электронную почту. 
          Номер вашего заказа: <span className="font-medium text-primary">ORD-{Math.floor(100000 + Math.random() * 900000)}</span>
        </p>
        <div className="flex flex-col md:flex-row gap-4 justify-center">
          <Button 
            className="bg-primary hover:bg-primary/90 text-white rounded-none py-6"
            asChild
          >
            <Link href="/catalog">
              Продолжить покупки
            </Link>
          </Button>
          <Button 
            variant="outline" 
            className="border-primary text-primary hover:bg-primary/5 rounded-none py-6"
            asChild
          >
            <Link href="/">
              Вернуться на главную
            </Link>
          </Button>
        </div>
      </motion.div>
    )
  }

  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="/cart" 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>

        <div className="grid md:grid-cols-3 gap-8 md:gap-12">
          {/* Checkout Form */}
          <motion.div 
            ref={ref1}
            initial="hidden"
            animate={inView1 ? "visible" : "hidden"}
            variants={staggerContainer}
            className="md:col-span-2 space-y-8"
          >
            {/* Step 1: Contact Information */}
            <motion.div 
              variants={fadeIn}
              className={`transition-opacity duration-300 ${step !== 1 && "opacity-60"}`}
            >
              <div className="flex items-center mb-6">
                <div className="bg-primary text-white w-10 h-10 rounded-full flex items-center justify-center mr-4 font-medium">
                  1
                </div>
                <h2 className="text-xl font-medium text-primary">Контактная информация</h2>
              </div>

              <AnimatePresence mode="wait">
                {step === 1 && (
                  <motion.div 
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className="space-y-6 p-6 border border-gray-200 shadow-sm bg-white"
                  >
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div className="space-y-2">
                        <Label htmlFor="firstName" className="text-gray-700">
                          Имя
                        </Label>
                        <Input 
                          id="firstName" 
                          placeholder="Введите имя" 
                          className="border-gray-200 focus:border-primary focus:ring-primary rounded-none"
                          value={formData.firstName}
                          onChange={handleChange}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="lastName" className="text-gray-700">
                          Фамилия
                        </Label>
                        <Input 
                          id="lastName" 
                          placeholder="Введите фамилию" 
                          className="border-gray-200 focus:border-primary focus:ring-primary rounded-none"
                          value={formData.lastName}
                          onChange={handleChange}
                        />
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="email" className="text-gray-700">
                        Email
                      </Label>
                      <Input 
                        id="email" 
                        type="email" 
                        placeholder="example@mail.com" 
                        className="border-gray-200 focus:border-primary focus:ring-primary rounded-none"
                        value={formData.email}
                        onChange={handleChange}
                      />
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="phone" className="text-gray-700">
                        Телефон
                      </Label>
                      <Input 
                        id="phone" 
                        placeholder="+7 (___) ___-__-__" 
                        className="border-gray-200 focus:border-primary focus:ring-primary rounded-none"
                        value={formData.phone}
                        onChange={handleChange}
                      />
                    </div>

                    <Button
                      className="w-full md:w-auto bg-primary hover:bg-primary/90 text-white rounded-none py-6 px-8 transition-colors duration-200"
                      onClick={() => setStep(2)}
                      disabled={!formData.firstName || !formData.email || !formData.phone}
                    >
                      Продолжить
                    </Button>
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.div>

            {/* Step 2: Shipping */}
            <motion.div 
              variants={fadeIn}
              className={`transition-opacity duration-300 ${step !== 2 && "opacity-60"}`}
            >
              <div className="flex items-center mb-6">
                <div className={`w-10 h-10 rounded-full flex items-center justify-center mr-4 font-medium ${step >= 2 ? "bg-primary text-white" : "bg-gray-200 text-gray-500"}`}>
                  2
                </div>
                <h2 className="text-xl font-medium text-primary">Доставка</h2>
              </div>

              <AnimatePresence mode="wait">
                {step === 2 && (
                  <motion.div 
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className="space-y-6 p-6 border border-gray-200 shadow-sm bg-white"
                  >
                    <RadioGroup 
                      defaultValue={formData.deliveryMethod}
                      onValueChange={(value) => handleRadioChange("deliveryMethod", value)}
                      className="space-y-4"
                    >
                      <div className="flex items-start space-x-3 p-4 border border-gray-200 hover:border-primary/20 transition-colors">
                        <RadioGroupItem value="courier" id="courier" className="mt-1" />
                        <div className="flex-1">
                          <Label htmlFor="courier" className="text-base font-medium text-primary">
                            Курьерская доставка
                          </Label>
                          <p className="text-sm text-gray-600">Доставка курьером по адресу</p>
                          <p className="text-sm font-medium text-primary mt-1">500 ₽</p>
                        </div>
                      </div>

                      <div className="flex items-start space-x-3 p-4 border border-gray-200 hover:border-primary/20 transition-colors">
                        <RadioGroupItem value="pickup" id="pickup" className="mt-1" />
                        <div className="flex-1">
                          <Label htmlFor="pickup" className="text-base font-medium text-primary">
                            Самовывоз из пункта выдачи
                          </Label>
                          <p className="text-sm text-gray-600">Выберите удобный пункт выдачи</p>
                          <p className="text-sm font-medium text-primary mt-1">300 ₽</p>
                        </div>
                      </div>

                      <div className="flex items-start space-x-3 p-4 border border-gray-200 hover:border-primary/20 transition-colors">
                        <RadioGroupItem value="post" id="post" className="mt-1" />
                        <div className="flex-1">
                          <Label htmlFor="post" className="text-base font-medium text-primary">
                            Почта России
                          </Label>
                          <p className="text-sm text-gray-600">Доставка в отделение Почты России</p>
                          <p className="text-sm font-medium text-primary mt-1">400 ₽</p>
                        </div>
                      </div>
                    </RadioGroup>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4">
                      <div className="space-y-2">
                        <Label htmlFor="address" className="text-gray-700">
                          Адрес доставки
                        </Label>
                        <Input 
                          id="address" 
                          placeholder="Улица, дом, квартира" 
                          className="border-gray-200 focus:border-primary focus:ring-primary rounded-none"
                          value={formData.address}
                          onChange={handleChange}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="city" className="text-gray-700">
                          Город
                        </Label>
                        <Input 
                          id="city" 
                          placeholder="Введите город" 
                          className="border-gray-200 focus:border-primary focus:ring-primary rounded-none"
                          value={formData.city}
                          onChange={handleChange}
                        />
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="postalCode" className="text-gray-700">
                        Почтовый индекс
                      </Label>
                      <Input 
                        id="postalCode" 
                        placeholder="Введите индекс" 
                        className="border-gray-200 focus:border-primary focus:ring-primary rounded-none max-w-xs"
                        value={formData.postalCode}
                        onChange={handleChange}
                      />
                    </div>

                    <div className="flex flex-wrap gap-4 pt-4">
                      <Button
                        variant="outline"
                        className="border-gray-300 text-gray-700 hover:bg-gray-50 rounded-none py-6 px-8 transition-colors duration-200"
                        onClick={() => setStep(1)}
                      >
                        Назад
                      </Button>
                      <Button
                        className="bg-primary hover:bg-primary/90 text-white rounded-none py-6 px-8 transition-colors duration-200"
                        onClick={() => setStep(3)}
                        disabled={!formData.address || !formData.city}
                      >
                        Продолжить
                      </Button>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.div>

            {/* Step 3: Payment */}
            <motion.div 
              variants={fadeIn}
              className={`transition-opacity duration-300 ${step !== 3 && "opacity-60"}`}
            >
              <div className="flex items-center mb-6">
                <div className={`w-10 h-10 rounded-full flex items-center justify-center mr-4 font-medium ${step >= 3 ? "bg-primary text-white" : "bg-gray-200 text-gray-500"}`}>
                  3
                </div>
                <h2 className="text-xl font-medium text-primary">Оплата</h2>
              </div>

              <AnimatePresence mode="wait">
                {step === 3 && (
                  <motion.div 
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className="space-y-6 p-6 border border-gray-200 shadow-sm bg-white"
                  >
                    <RadioGroup 
                      defaultValue={formData.paymentMethod}
                      onValueChange={(value) => handleRadioChange("paymentMethod", value)}
                      className="space-y-4"
                    >
                      <div className="flex items-start space-x-3 p-4 border border-gray-200 hover:border-primary/20 transition-colors">
                        <RadioGroupItem value="card" id="card" className="mt-1" />
                        <div className="flex-1">
                          <Label htmlFor="card" className="text-base font-medium text-primary flex items-center">
                            <CreditCard className="h-5 w-5 mr-2" />
                            Банковская карта
                          </Label>
                          <p className="text-sm text-gray-600">Visa, MasterCard, МИР</p>
                        </div>
                      </div>

                      <div className="flex items-start space-x-3 p-4 border border-gray-200 hover:border-primary/20 transition-colors">
                        <RadioGroupItem value="cash" id="cash" className="mt-1" />
                        <div className="flex-1">
                          <Label htmlFor="cash" className="text-base font-medium text-primary">
                            Наличными при получении
                          </Label>
                          <p className="text-sm text-gray-600">Оплата курьеру или в пункте выдачи</p>
                        </div>
                      </div>
                    </RadioGroup>

                    <div className="space-y-2 pt-4">
                      <Label htmlFor="comment" className="text-gray-700">
                        Комментарий к заказу (необязательно)
                      </Label>
                      <Textarea 
                        id="comment" 
                        placeholder="Введите комментарий к заказу" 
                        className="border-gray-200 focus:border-primary focus:ring-primary rounded-none min-h-[100px]"
                        value={formData.comment}
                        onChange={handleChange}
                      />
                    </div>

                    <div className="flex flex-wrap gap-4 pt-4">
                      <Button
                        variant="outline"
                        className="border-gray-300 text-gray-700 hover:bg-gray-50 rounded-none py-6 px-8 transition-colors duration-200"
                        onClick={() => setStep(2)}
                      >
                        Назад
                      </Button>
                      <Button
                        className="bg-primary hover:bg-primary/90 text-white rounded-none py-6 px-8 transition-colors duration-200"
                        onClick={handleSubmit}
                      >
                        Оформить заказ
                      </Button>
                    </div>
                  </motion.div>
                )}
              </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">
                {cartItems.map((item) => (
                  <div key={item.id} className="flex gap-4">
                    <div className="relative w-16 h-20 flex-shrink-0">
                      <Image src={item.image} alt={item.name} fill className="object-cover" />
                    </div>
                    <div className="flex-1">
                      <p className="text-sm font-medium text-primary line-clamp-2">{item.name}</p>
                      <div className="text-xs text-gray-500 mt-1">
                        <span>Размер: {item.size}</span>
                        <span className="mx-2">•</span>
                        <span>Цвет: {item.color}</span>
                      </div>
                      <div className="flex justify-between mt-2">
                        <span className="text-xs text-gray-500">{item.quantity} × {item.price.toLocaleString()} ₽</span>
                        <span className="text-sm font-medium">{(item.price * item.quantity).toLocaleString()} ₽</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              <Separator className="my-6" />

              <div className="space-y-3 text-sm">
                <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.toLocaleString()} ₽</span>
                </div>

                <Separator className="my-4" />

                <div className="flex justify-between font-medium text-lg">
                  <span>Итого:</span>
                  <span className="text-primary">{total.toLocaleString()} ₽</span>
                </div>
              </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">Доставка по всей России</span>
                </div>
                <div className="flex items-center gap-3">
                  <Clock className="h-5 w-5 text-primary flex-shrink-0" />
                  <span className="text-sm">Срок доставки 1-3 рабочих дня</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>
      </div>
    </div>
  )
}

