import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { Sparkles, Calendar, Package, Ruler, CheckCircle, ArrowRight, Zap, Crown, Award, Heart, Star, Users, Clock, TrendingUp } from 'lucide-react'
import './RentCostume.css'

const RentCostume = () => {
  const navigate = useNavigate()
  const [selectedCategory, setSelectedCategory] = useState('')
  const [selectedTheme, setSelectedTheme] = useState('')
  const [selectedSize, setSelectedSize] = useState('')
  const [returnDate, setReturnDate] = useState('')
  const [isSubmitted, setIsSubmitted] = useState(false)

  const categories = [
    { 
      id: 'era', 
      name: 'Эпоха', 
      icon: Crown,
      color: '#C41E3A',
      gradient: 'linear-gradient(135deg, #C41E3A 0%, #E63946 100%)',
      description: 'Исторические костюмы разных эпох',
      examples: ['Средневековье', 'Ренессанс', 'Викторианская эпоха']
    },
    { 
      id: 'theme', 
      name: 'Тематика', 
      icon: Sparkles,
      color: '#FF6B35',
      gradient: 'linear-gradient(135deg, #FF6B35 0%, #FFB627 100%)',
      description: 'Костюмы по тематикам и жанрам',
      examples: ['Фэнтези', 'Пираты', 'Супергерои']
    },
    { 
      id: 'size', 
      name: 'Размер', 
      icon: Ruler,
      color: '#FFB627',
      gradient: 'linear-gradient(135deg, #FFB627 0%, #FFD93D 100%)',
      description: 'Выбор по размеру',
      examples: ['XS-XXL', 'Детские', 'Большие размеры']
    }
  ]

  const themes = {
    era: [
      { id: 'medieval', name: 'Средневековье', icon: Crown },
      { id: 'renaissance', name: 'Ренессанс', icon: Award },
      { id: 'victorian', name: 'Викторианская', icon: Heart }
    ],
    theme: [
      { id: 'fantasy', name: 'Фэнтези', icon: Sparkles },
      { id: 'pirate', name: 'Пираты', icon: Package },
      { id: 'superhero', name: 'Супергерои', icon: Zap }
    ],
    size: [
      { id: 'xs-xl', name: 'XS-XXL', icon: Ruler },
      { id: 'kids', name: 'Детские', icon: Users },
      { id: 'plus', name: 'Большие размеры', icon: TrendingUp }
    ]
  }

  const sizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL']

  const processSteps = [
    { icon: Package, title: 'Выберите костюм', description: 'Просмотрите наш каталог и выберите подходящий костюм', step: '01' },
    { icon: Calendar, title: 'Укажите даты', description: 'Выберите дату аренды и возврата', step: '02' },
    { icon: CheckCircle, title: 'Подтвердите заказ', description: 'Оформите заказ и получите подтверждение', step: '03' },
    { icon: Sparkles, title: 'Наслаждайтесь', description: 'Получите костюм и создайте незабываемое мероприятие', step: '04' }
  ]

  const handleSubmit = (e) => {
    e.preventDefault()
    if (selectedCategory && selectedTheme && selectedSize && returnDate) {
      const savedRentals = localStorage.getItem('costumeRentals')
      const rentals = savedRentals ? JSON.parse(savedRentals) : []
      
      const categoryData = categories.find(c => c.id === selectedCategory)
      const themeData = themes[selectedCategory]?.find(t => t.id === selectedTheme)
      
      const newRental = {
        id: Date.now(),
        costume: themeData?.name || 'Костюм',
        date: new Date().toISOString().split('T')[0],
        duration: '3 дня',
        review: '',
        rating: 0,
        category: categoryData?.name || 'Категория'
      }

      rentals.push(newRental)
      localStorage.setItem('costumeRentals', JSON.stringify(rentals))
      
      setIsSubmitted(true)
      setTimeout(() => {
        setIsSubmitted(false)
        setSelectedCategory('')
        setSelectedTheme('')
        setSelectedSize('')
        setReturnDate('')
        navigate('/')
      }, 2000)
    }
  }

  const minDate = new Date().toISOString().split('T')[0]
  const maxDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]

  return (
    <div className="rent-costume">
      <div className="container">
        <motion.section 
          className="rent-hero-asymmetric"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.8 }}
        >
          <div className="rent-hero-split">
            <motion.div 
              className="rent-hero-left"
              initial={{ x: -80, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              transition={{ duration: 0.8, delay: 0.2 }}
            >
              <div className="rent-step-indicator">ШАГ 1</div>
              <h1 className="rent-title-asymmetric">Арендовать костюм</h1>
              <div className="rent-accent-line"></div>
            </motion.div>
            <motion.div 
              className="rent-hero-right"
              initial={{ x: 80, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              transition={{ duration: 0.8, delay: 0.3 }}
            >
              <p className="rent-description-asymmetric">
                Создайте незабываемый образ для вашего мероприятия. 
                Выберите категорию, тематику и размер.
              </p>
            </motion.div>
          </div>
        </motion.section>

        <motion.section 
          className="rental-form-asymmetric"
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7, delay: 0.4 }}
        >
          <div className="form-container-asymmetric">
            <form className="rental-form-asymmetric-inner" onSubmit={handleSubmit}>
              <div className="form-section-asymmetric">
                <div className="form-label-asymmetric">
                  <Package size={32} strokeWidth={2.5} className="label-icon-asymmetric" />
                  <span className="label-text-asymmetric">Категория костюма</span>
                </div>
                <div className="categories-staggered">
                  {categories.map((category, index) => {
                    const IconComponent = category.icon
                    return (
                      <motion.button
                        key={category.id}
                        type="button"
                        className={`category-staggered-card ${selectedCategory === category.id ? 'selected' : ''}`}
                        onClick={() => {
                          setSelectedCategory(category.id)
                          setSelectedTheme('')
                        }}
                        initial={{ opacity: 0, x: index % 2 === 0 ? -60 : 60, rotate: index % 2 === 0 ? -5 : 5 }}
                        animate={{ opacity: 1, x: 0, rotate: 0 }}
                        transition={{ delay: 0.5 + index * 0.15, duration: 0.6, type: "spring" }}
                        whileHover={{ 
                          rotate: index % 2 === 0 ? 2 : -2, 
                          scale: 1.05,
                          y: -8,
                          transition: { duration: 0.3 } 
                        }}
                        style={{ 
                          background: selectedCategory === category.id ? category.gradient : 'white',
                          borderColor: selectedCategory === category.id ? 'transparent' : category.color + '40'
                        }}
                      >
                        <div className="category-staggered-icon" style={{ 
                          background: selectedCategory === category.id ? 'rgba(255, 255, 255, 0.25)' : category.color + '15',
                          borderColor: selectedCategory === category.id ? 'rgba(255, 255, 255, 0.4)' : category.color + '30'
                        }}>
                          <IconComponent size={48} strokeWidth={2.5} color={selectedCategory === category.id ? 'white' : category.color} />
                        </div>
                        <div className="category-staggered-content">
                          <h3 className="category-staggered-name" style={{ color: selectedCategory === category.id ? 'white' : '#1A1A1A' }}>
                            {category.name}
                          </h3>
                          <p className="category-staggered-description" style={{ color: selectedCategory === category.id ? 'rgba(255, 255, 255, 0.9)' : '#6B6B6B' }}>
                            {category.description}
                          </p>
                          <div className="category-examples-staggered">
                            {category.examples.map((example, exIndex) => (
                              <span 
                                key={exIndex} 
                                className="example-badge-staggered"
                                style={{ 
                                  background: selectedCategory === category.id ? 'rgba(255, 255, 255, 0.2)' : category.color + '10',
                                  color: selectedCategory === category.id ? 'white' : category.color
                                }}
                              >
                                {example}
                              </span>
                            ))}
                          </div>
                        </div>
                        {selectedCategory === category.id && (
                          <motion.div 
                            className="category-check-staggered"
                            initial={{ scale: 0, rotate: -180 }}
                            animate={{ scale: 1, rotate: 0 }}
                            transition={{ type: "spring", stiffness: 200, damping: 15 }}
                          >
                            <CheckCircle size={36} strokeWidth={2.5} color="white" />
                          </motion.div>
                        )}
                      </motion.button>
                    )
                  })}
                </div>
              </div>

              {selectedCategory && (
                <motion.div 
                  className="form-section-asymmetric"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  transition={{ duration: 0.6 }}
                >
                  <div className="form-label-asymmetric">
                    <Sparkles size={32} strokeWidth={2.5} className="label-icon-asymmetric" />
                    <span className="label-text-asymmetric">Тематика / Подкатегория</span>
                  </div>
                  <div className="themes-staggered">
                    {themes[selectedCategory]?.map((theme, index) => {
                      const IconComponent = theme.icon
                      const categoryData = categories.find(c => c.id === selectedCategory)
                      return (
                        <motion.button
                          key={theme.id}
                          type="button"
                          className={`theme-staggered-card ${selectedTheme === theme.id ? 'selected' : ''}`}
                          onClick={() => setSelectedTheme(theme.id)}
                          initial={{ opacity: 0, scale: 0.8, rotate: -10 }}
                          animate={{ opacity: 1, scale: 1, rotate: 0 }}
                          transition={{ delay: 0.1 + index * 0.1, duration: 0.5, type: "spring" }}
                          whileHover={{ 
                            scale: 1.1, 
                            rotate: 5,
                            y: -6,
                            transition: { duration: 0.2 } 
                          }}
                          style={{
                            background: selectedTheme === theme.id ? categoryData?.gradient : 'white',
                            borderColor: selectedTheme === theme.id ? 'transparent' : categoryData?.color + '40'
                          }}
                        >
                          <div className="theme-staggered-icon" style={{
                            background: selectedTheme === theme.id ? 'rgba(255, 255, 255, 0.25)' : categoryData?.color + '15'
                          }}>
                            <IconComponent size={40} strokeWidth={2.5} color={selectedTheme === theme.id ? 'white' : categoryData?.color} />
                          </div>
                          <span className="theme-staggered-name" style={{ color: selectedTheme === theme.id ? 'white' : '#1A1A1A' }}>
                            {theme.name}
                          </span>
                          {selectedTheme === theme.id && (
                            <motion.div 
                              className="theme-check-staggered"
                              initial={{ scale: 0 }}
                              animate={{ scale: 1 }}
                              transition={{ type: "spring", stiffness: 200, damping: 15 }}
                            >
                              <CheckCircle size={24} strokeWidth={2.5} color="white" />
                            </motion.div>
                          )}
                        </motion.button>
                      )
                    })}
                  </div>
                </motion.div>
              )}

              {selectedTheme && (
                <motion.div 
                  className="form-section-asymmetric"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  transition={{ duration: 0.6 }}
                >
                  <div className="form-label-asymmetric">
                    <Ruler size={32} strokeWidth={2.5} className="label-icon-asymmetric" />
                    <span className="label-text-asymmetric">Размер костюма</span>
                  </div>
                  <div className="sizes-staggered">
                    {sizes.map((size, index) => {
                      const categoryData = categories.find(c => c.id === selectedCategory)
                      return (
                        <motion.button
                          key={size}
                          type="button"
                          className={`size-staggered-card ${selectedSize === size ? 'selected' : ''}`}
                          onClick={() => setSelectedSize(size)}
                          initial={{ opacity: 0, scale: 0.5, rotate: -180 }}
                          animate={{ opacity: 1, scale: 1, rotate: 0 }}
                          transition={{ delay: 0.05 + index * 0.08, duration: 0.5, type: "spring" }}
                          whileHover={{ scale: 1.15, rotate: 10, transition: { duration: 0.2 } }}
                          whileTap={{ scale: 0.9 }}
                          style={{
                            background: selectedSize === size ? categoryData?.gradient : 'white',
                            borderColor: selectedSize === size ? 'transparent' : categoryData?.color + '40',
                            color: selectedSize === size ? 'white' : '#1A1A1A'
                          }}
                        >
                          {size}
                          {selectedSize === size && (
                            <motion.div 
                              className="size-check-staggered"
                              initial={{ scale: 0 }}
                              animate={{ scale: 1 }}
                              transition={{ type: "spring", stiffness: 200, damping: 15 }}
                            >
                              <CheckCircle size={20} strokeWidth={2.5} color="white" />
                            </motion.div>
                          )}
                        </motion.button>
                      )
                    })}
                  </div>
                </motion.div>
              )}

              <div className="form-section-asymmetric date-section-asymmetric">
                <div className="date-label-asymmetric">
                  <Calendar size={36} strokeWidth={2.5} className="label-icon-asymmetric" />
                  <div className="date-label-content-asymmetric">
                    <span className="date-label-title-asymmetric">Дата возврата костюма</span>
                    <span className="date-label-hint-asymmetric">Максимальный срок аренды: 30 дней</span>
                  </div>
                </div>
                <div className="date-input-wrapper-asymmetric">
                  <input
                    type="date"
                    id="returnDate"
                    className="form-input-asymmetric"
                    value={returnDate}
                    onChange={(e) => setReturnDate(e.target.value)}
                    min={minDate}
                    max={maxDate}
                    required
                  />
                  <div className="date-input-decoration-asymmetric"></div>
                </div>
              </div>

              <motion.button 
                type="submit" 
                className="submit-button-asymmetric" 
                disabled={!selectedCategory || !selectedTheme || !selectedSize || !returnDate}
                whileHover={{ scale: 1.05, y: -4, rotate: 1 }}
                whileTap={{ scale: 0.95 }}
              >
                <span>Оформить аренду</span>
                <ArrowRight size={32} strokeWidth={2.5} className="btn-icon-asymmetric" />
              </motion.button>

              {isSubmitted && (
                <motion.div 
                  className="success-message-asymmetric"
                  initial={{ opacity: 0, scale: 0.8, rotate: -10 }}
                  animate={{ opacity: 1, scale: 1, rotate: 0 }}
                  transition={{ duration: 0.5, type: "spring" }}
                >
                  <CheckCircle size={48} strokeWidth={2.5} className="success-icon-asymmetric" />
                  <span>Аренда успешно оформлена!</span>
                </motion.div>
              )}
            </form>
          </div>
        </motion.section>

        <motion.section 
          className="process-steps-asymmetric"
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7, delay: 0.6 }}
        >
          <div className="process-header-asymmetric">
            <div className="process-accent-line"></div>
            <h2 className="process-title-asymmetric">Как это работает</h2>
          </div>
          <div className="process-steps-grid-asymmetric">
            {processSteps.map((step, index) => {
              const IconComponent = step.icon
              return (
                <motion.div
                  key={step.title}
                  className="process-step-asymmetric"
                  initial={{ opacity: 0, y: 60, rotate: index % 2 === 0 ? -10 : 10 }}
                  animate={{ opacity: 1, y: 0, rotate: 0 }}
                  transition={{ delay: 0.7 + index * 0.15, duration: 0.6, type: "spring" }}
                  whileHover={{ 
                    rotate: index % 2 === 0 ? 3 : -3, 
                    scale: 1.08,
                    y: -10,
                    transition: { duration: 0.3 } 
                  }}
                >
                  <div className="process-step-number">{step.step}</div>
                  <div className="process-step-icon-wrapper">
                    <IconComponent size={52} strokeWidth={2.5} color="#C41E3A" />
                  </div>
                  <h3 className="process-step-title">{step.title}</h3>
                  <p className="process-step-description">{step.description}</p>
                </motion.div>
              )
            })}
          </div>
        </motion.section>
      </div>
    </div>
  )
}

export default RentCostume
