import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { Calendar, Package, Ruler, CheckCircle, ArrowRight, Shirt, Crown, Sparkles, Users, TrendingUp, CheckCircle2, Star, Zap } 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: '#6366F1',
      description: 'Исторические костюмы разных эпох',
      examples: ['Средневековье', 'Ренессанс', 'Викторианская']
    },
    { 
      id: 'theme', 
      name: 'Тематика', 
      icon: Sparkles,
      color: '#8B5CF6',
      description: 'Костюмы по тематикам и жанрам',
      examples: ['Фэнтези', 'Пираты', 'Супергерои']
    },
    { 
      id: 'size', 
      name: 'Размер', 
      icon: Ruler,
      color: '#A78BFA',
      description: 'Выбор по размеру',
      examples: ['XS-XXL', 'Детские', 'Большие']
    }
  ]

  const themes = {
    era: [
      { id: 'medieval', name: 'Средневековье', icon: Crown },
      { id: 'renaissance', name: 'Ренессанс', icon: CheckCircle2 },
      { id: 'victorian', name: 'Викторианская', icon: Star }
    ],
    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 guarantees = [
    { icon: CheckCircle2, title: 'Гарантия качества', text: 'Все костюмы проходят проверку перед выдачей', metric: '100%' },
    { icon: Calendar, title: 'Гибкие сроки', text: 'Возможность продления аренды', metric: '24/7' },
    { icon: Star, title: 'Премиум сервис', text: 'Индивидуальный подход к каждому клиенту', metric: '100%' },
    { icon: Package, title: 'Быстрая доставка', text: 'Доставка в день заказа', metric: '1 день' }
  ]

  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-modular"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.8 }}
        >
          <div className="rent-hero-modular-grid">
            <motion.div 
              className="rent-hero-modular-main"
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: 0.2 }}
            >
              <div className="rent-modular-line"></div>
              <h1 className="rent-modular-title">Арендовать костюм</h1>
            </motion.div>
            <motion.div 
              className="rent-hero-modular-side"
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: 0.3 }}
            >
              <p className="rent-modular-description">
                Выберите категорию, тематику и размер для вашего мероприятия
              </p>
            </motion.div>
          </div>
        </motion.section>

        <motion.section 
          className="rental-form-modular"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7, delay: 0.4 }}
        >
          <div className="form-container-modular">
            <form className="rental-form-modular-inner" onSubmit={handleSubmit}>
              <div className="form-section-modular">
                <div className="form-label-modular">
                  <Package size={28} strokeWidth={2} className="label-icon-modular" />
                  <span className="label-text-modular">Категория костюма</span>
                </div>
                <div className="categories-modular-list">
                  {categories.map((category, index) => {
                    const IconComponent = category.icon
                    return (
                      <motion.button
                        key={category.id}
                        type="button"
                        className={`category-modular-item ${selectedCategory === category.id ? 'selected' : ''}`}
                        onClick={() => {
                          setSelectedCategory(category.id)
                          setSelectedTheme('')
                        }}
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.5 + index * 0.1, duration: 0.5 }}
                        whileHover={{ y: -4, transition: { duration: 0.2 } }}
                      >
                        <div className="category-modular-icon" style={{ 
                          background: selectedCategory === category.id ? `${category.color}15` : 'rgba(99, 102, 241, 0.05)',
                          borderColor: selectedCategory === category.id ? category.color : 'rgba(99, 102, 241, 0.2)'
                        }}>
                          <IconComponent size={32} strokeWidth={2} color={selectedCategory === category.id ? category.color : '#6366F1'} />
                        </div>
                        <div className="category-modular-content">
                          <h3 className="category-modular-name">{category.name}</h3>
                          <p className="category-modular-description">{category.description}</p>
                          <div className="category-examples-modular">
                            {category.examples.map((example, exIndex) => (
                              <span 
                                key={exIndex} 
                                className="example-badge-modular"
                                style={{ 
                                  background: selectedCategory === category.id ? `${category.color}10` : 'rgba(99, 102, 241, 0.05)',
                                  color: selectedCategory === category.id ? category.color : '#6366F1'
                                }}
                              >
                                {example}
                              </span>
                            ))}
                          </div>
                        </div>
                        {selectedCategory === category.id && (
                          <motion.div 
                            className="category-check-modular"
                            initial={{ scale: 0 }}
                            animate={{ scale: 1 }}
                            transition={{ type: "spring", stiffness: 200, damping: 15 }}
                          >
                            <CheckCircle size={24} strokeWidth={2} color={category.color} />
                          </motion.div>
                        )}
                      </motion.button>
                    )
                  })}
                </div>
              </div>

              {selectedCategory && (
                <motion.div 
                  className="form-section-modular"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  transition={{ duration: 0.5 }}
                >
                  <div className="form-label-modular">
                    <Sparkles size={28} strokeWidth={2} className="label-icon-modular" />
                    <span className="label-text-modular">Тематика / Подкатегория</span>
                  </div>
                  <div className="themes-modular-list">
                    {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-modular-item ${selectedTheme === theme.id ? 'selected' : ''}`}
                          onClick={() => setSelectedTheme(theme.id)}
                          initial={{ opacity: 0, scale: 0.9 }}
                          animate={{ opacity: 1, scale: 1 }}
                          transition={{ delay: 0.1 + index * 0.1, duration: 0.4 }}
                          whileHover={{ scale: 1.05, transition: { duration: 0.2 } }}
                          style={{
                            borderColor: selectedTheme === theme.id ? categoryData?.color : 'rgba(99, 102, 241, 0.2)',
                            background: selectedTheme === theme.id ? `${categoryData?.color}10` : 'white'
                          }}
                        >
                          <div className="theme-modular-icon" style={{
                            background: selectedTheme === theme.id ? `${categoryData?.color}15` : 'rgba(99, 102, 241, 0.05)'
                          }}>
                            <IconComponent size={28} strokeWidth={2} color={selectedTheme === theme.id ? categoryData?.color : '#6366F1'} />
                          </div>
                          <span className="theme-modular-name">{theme.name}</span>
                          {selectedTheme === theme.id && (
                            <motion.div 
                              className="theme-check-modular"
                              initial={{ scale: 0 }}
                              animate={{ scale: 1 }}
                              transition={{ type: "spring", stiffness: 200, damping: 15 }}
                            >
                              <CheckCircle size={20} strokeWidth={2} color={categoryData?.color} />
                            </motion.div>
                          )}
                        </motion.button>
                      )
                    })}
                  </div>
                </motion.div>
              )}

              {selectedTheme && (
                <motion.div 
                  className="form-section-modular"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  transition={{ duration: 0.5 }}
                >
                  <div className="form-label-modular">
                    <Ruler size={28} strokeWidth={2} className="label-icon-modular" />
                    <span className="label-text-modular">Размер костюма</span>
                  </div>
                  <div className="sizes-modular-list">
                    {sizes.map((size, index) => {
                      const categoryData = categories.find(c => c.id === selectedCategory)
                      return (
                        <motion.button
                          key={size}
                          type="button"
                          className={`size-modular-item ${selectedSize === size ? 'selected' : ''}`}
                          onClick={() => setSelectedSize(size)}
                          initial={{ opacity: 0, scale: 0.9 }}
                          animate={{ opacity: 1, scale: 1 }}
                          transition={{ delay: 0.05 + index * 0.05, duration: 0.3 }}
                          whileHover={{ scale: 1.08, transition: { duration: 0.2 } }}
                          whileTap={{ scale: 0.95 }}
                          style={{
                            borderColor: selectedSize === size ? categoryData?.color : 'rgba(99, 102, 241, 0.2)',
                            background: selectedSize === size ? `${categoryData?.color}10` : 'white',
                            color: selectedSize === size ? categoryData?.color : '#6366F1'
                          }}
                        >
                          {size}
                          {selectedSize === size && (
                            <motion.div 
                              className="size-check-modular"
                              initial={{ scale: 0 }}
                              animate={{ scale: 1 }}
                              transition={{ type: "spring", stiffness: 200, damping: 15 }}
                            >
                              <CheckCircle size={18} strokeWidth={2} color={categoryData?.color} />
                            </motion.div>
                          )}
                        </motion.button>
                      )
                    })}
                  </div>
                </motion.div>
              )}

              <div className="form-section-modular date-section-modular">
                <div className="date-label-modular">
                  <Calendar size={28} strokeWidth={2} className="label-icon-modular" />
                  <span className="date-label-text-modular">Дата возврата костюма</span>
                </div>
                <input
                  type="date"
                  id="returnDate"
                  className="form-input-modular"
                  value={returnDate}
                  onChange={(e) => setReturnDate(e.target.value)}
                  min={minDate}
                  max={maxDate}
                  required
                />
              </div>

              <motion.button 
                type="submit" 
                className="submit-button-modular" 
                disabled={!selectedCategory || !selectedTheme || !selectedSize || !returnDate}
                whileHover={{ scale: 1.02, y: -2 }}
                whileTap={{ scale: 0.98 }}
              >
                <span>Оформить аренду</span>
                <ArrowRight size={24} strokeWidth={2} className="btn-icon-modular" />
              </motion.button>

              {isSubmitted && (
                <motion.div 
                  className="success-message-modular"
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ duration: 0.4 }}
                >
                  <CheckCircle size={32} strokeWidth={2} className="success-icon-modular" />
                  <span>Аренда успешно оформлена!</span>
                </motion.div>
              )}
            </form>
          </div>
        </motion.section>

        <motion.section 
          className="guarantees-modular-section"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7, delay: 0.5 }}
        >
          <div className="guarantees-modular-header">
            <div className="section-modular-line"></div>
            <h2 className="section-modular-title">Наши гарантии</h2>
          </div>
          <div className="guarantees-modular-grid">
            {guarantees.map((guarantee, index) => {
              const IconComponent = guarantee.icon
              return (
                <motion.div
                  key={guarantee.title}
                  className="guarantee-modular-card"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.6 + index * 0.1, duration: 0.5 }}
                  whileHover={{ y: -4, transition: { duration: 0.2 } }}
                >
                  <div className="guarantee-modular-metric">{guarantee.metric}</div>
                  <div className="guarantee-modular-icon">
                    <IconComponent size={32} strokeWidth={2} color="#6366F1" />
                  </div>
                  <h3 className="guarantee-modular-title">{guarantee.title}</h3>
                  <p className="guarantee-modular-text">{guarantee.text}</p>
                  <div className="guarantee-modular-accent"></div>
                </motion.div>
              )
            })}
          </div>
        </motion.section>
      </div>
    </div>
  )
}

export default RentCostume
