import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { Calendar, Brush, Palette, CheckCircle, ArrowRight, Paintbrush, PenTool, Layers, Monitor, Sparkles } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './Enroll.css'

const Enroll = () => {
  const navigate = useNavigate()
  const [selectedStyle, setSelectedStyle] = useState('')
  const [selectedDate, setSelectedDate] = useState('')
  const [isSubmitted, setIsSubmitted] = useState(false)
  const [currentStep, setCurrentStep] = useState(1)

  const styles = [
    { 
      id: 'watercolor', 
      name: 'Акварель', 
      icon: Paintbrush,
      color: '#4A90E2',
      gradient: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
      description: 'Легкость и прозрачность красок. Идеально для пейзажей и портретов.',
      duration: '2 часа',
      price: 'от 1200₽',
      features: ['Техника мокрым по мокрому', 'Работа с цветом', 'Создание атмосферы']
    },
    { 
      id: 'graphics', 
      name: 'Графика', 
      icon: PenTool,
      color: '#2C3E50',
      gradient: 'linear-gradient(135deg, #2C3E50 0%, #1A252F 100%)',
      description: 'Точность линий и штриховка. Классическая техника рисунка.',
      duration: '2.5 часа',
      price: 'от 1000₽',
      features: ['Работа с карандашом', 'Штриховка и тонировка', 'Композиция']
    },
    { 
      id: 'oil', 
      name: 'Масло', 
      icon: Layers,
      color: '#E74C3C',
      gradient: 'linear-gradient(135deg, #E74C3C 0%, #C0392B 100%)',
      description: 'Богатство цвета и фактуры. Профессиональная живопись.',
      duration: '3 часа',
      price: 'от 1500₽',
      features: ['Техника мазка', 'Работа с палитрой', 'Создание объема']
    },
    { 
      id: 'digital', 
      name: 'Цифровое', 
      icon: Monitor,
      color: '#9B59B6',
      gradient: 'linear-gradient(135deg, #9B59B6 0%, #8E44AD 100%)',
      description: 'Современные технологии в искусстве. Графические планшеты и программы.',
      duration: '2.5 часа',
      price: 'от 1300₽',
      features: ['Работа в Photoshop', 'Графические планшеты', 'Цифровая живопись']
    }
  ]

  const today = new Date()
  const maxDate = new Date(today.getTime() + 90 * 24 * 60 * 60 * 1000)
  const minDateStr = today.toISOString().split('T')[0]
  const maxDateStr = maxDate.toISOString().split('T')[0]

  const handleSubmit = (e) => {
    e.preventDefault()
    if (!selectedStyle || !selectedDate) return

    const saved = localStorage.getItem('drawingLessons')
    const lessons = saved ? JSON.parse(saved) : []
    
    const styleData = styles.find(s => s.id === selectedStyle)
    
    const newLesson = {
      id: Date.now(),
      technique: styleData.name,
      instructor: styleData.instructor || 'Преподаватель',
      date: selectedDate,
      rating: 0,
      workTitle: `Работа в технике ${styleData.name.toLowerCase()}`
    }
    
    lessons.push(newLesson)
    localStorage.setItem('drawingLessons', JSON.stringify(lessons))
    
    setIsSubmitted(true)
    setTimeout(() => {
      navigate('/')
    }, 2000)
  }

  return (
    <div className="enroll">
      <div className="container">
        <motion.section 
          className="enroll-hero-creative"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
        >
          <div className="hero-content-enroll">
            <motion.div 
              className="hero-badge-enroll"
              initial={{ scale: 0, rotate: -180 }}
              animate={{ scale: 1, rotate: 0 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
            >
              <Palette size={20} strokeWidth={2.5} />
              <span>НАЧНИТЕ ТВОРИТЬ</span>
            </motion.div>
            <h1 className="hero-title-enroll">
              Записаться на <span className="title-gradient-enroll">занятие</span>
            </h1>
            <p className="hero-description-enroll">
              Выберите стиль рисования и дату начала. Каждое занятие — это возможность 
              раскрыть свой творческий потенциал и научиться новым техникам.
            </p>
          </div>
        </motion.section>

        <motion.section 
          className="enroll-form-creative"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.8, delay: 0.3 }}
        >
          <div className="form-progress-creative">
            <div className="progress-steps-creative">
              <motion.div 
                className={`progress-step-creative ${currentStep >= 1 ? 'active' : ''}`}
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ delay: 0.4, type: "spring", stiffness: 200 }}
              >
                <div className="step-number-creative">1</div>
                <span>Стиль</span>
              </motion.div>
              <div className="progress-line-creative">
                <motion.div 
                  className="progress-fill-creative"
                  initial={{ width: 0 }}
                  animate={{ width: selectedStyle ? '100%' : '0%' }}
                  transition={{ duration: 0.5 }}
                />
              </div>
              <motion.div 
                className={`progress-step-creative ${currentStep >= 2 ? 'active' : ''}`}
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ delay: 0.5, type: "spring", stiffness: 200 }}
              >
                <div className="step-number-creative">2</div>
                <span>Дата</span>
              </motion.div>
              <div className="progress-line-creative">
                <motion.div 
                  className="progress-fill-creative"
                  initial={{ width: 0 }}
                  animate={{ width: selectedDate ? '100%' : '0%' }}
                  transition={{ duration: 0.5 }}
                />
              </div>
              <motion.div 
                className={`progress-step-creative ${currentStep >= 3 ? 'active' : ''}`}
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ delay: 0.6, type: "spring", stiffness: 200 }}
              >
                <div className="step-number-creative">3</div>
                <span>Готово</span>
              </motion.div>
            </div>
          </div>

          <form className="enroll-form-wrapper-creative" onSubmit={handleSubmit}>
            <div className="form-section-style">
              <div className="form-label-creative">
                <Brush size={28} strokeWidth={2.5} />
                <span className="label-text-creative">Выберите стиль рисования</span>
              </div>
              <div className="styles-palette">
                {styles.map((style, index) => {
                  const Icon = style.icon
                  const isSelected = selectedStyle === style.id
                  
                  return (
                    <motion.button
                      key={style.id}
                      type="button"
                      className={`style-card-creative ${isSelected ? 'selected' : ''}`}
                      onClick={() => {
                        setSelectedStyle(style.id)
                        setCurrentStep(2)
                      }}
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={{ delay: index * 0.05 }}
                      whileHover={{ y: -3 }}
                      whileTap={{ scale: 0.99 }}
                      style={isSelected ? { 
                        background: style.gradient,
                        borderColor: style.color 
                      } : {}}
                    >
                      <div className="style-icon-wrapper">
                        <div 
                          className="style-icon-creative"
                          style={{ 
                            borderColor: isSelected ? 'rgba(255, 255, 255, 0.3)' : style.color,
                            background: isSelected ? 'rgba(255, 255, 255, 0.2)' : 'rgba(255, 107, 157, 0.1)'
                          }}
                        >
                          <Icon 
                            size={48} 
                            strokeWidth={2.5}
                            style={{ color: isSelected ? 'white' : style.color }}
                          />
                        </div>
                        {isSelected && (
                          <div className="style-check-creative">
                            <CheckCircle size={32} strokeWidth={2.5} />
                          </div>
                        )}
                      </div>
                      <div className="style-content-creative">
                        <h3 className="style-name-creative" style={{ color: isSelected ? 'white' : 'var(--text)' }}>
                          {style.name}
                        </h3>
                        <p className="style-description-creative" style={{ color: isSelected ? 'rgba(255, 255, 255, 0.9)' : 'var(--text-light)' }}>
                          {style.description}
                        </p>
                        <div className="style-features-creative">
                          {style.features.map((feature, i) => (
                            <span 
                              key={i}
                              className="feature-tag-creative"
                              style={{ 
                                background: isSelected ? 'rgba(255, 255, 255, 0.2)' : 'rgba(255, 107, 157, 0.1)',
                                color: isSelected ? 'white' : 'var(--primary)'
                              }}
                            >
                              {feature}
                            </span>
                          ))}
                        </div>
                        <div className="style-meta-creative">
                          <div className="meta-item-creative">
                            <Calendar size={16} strokeWidth={2} />
                            <span>{style.duration}</span>
                          </div>
                          <div className="meta-item-creative">
                            <span>{style.price}</span>
                          </div>
                        </div>
                      </div>
                    </motion.button>
                  )
                })}
              </div>
            </div>

            <AnimatePresence>
              {selectedStyle && (
                <motion.div 
                  className="form-section-date-creative"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ duration: 0.4 }}
                  onAnimationComplete={() => setCurrentStep(3)}
                >
                  <div className="date-label-creative">
                    <Calendar size={28} strokeWidth={2.5} />
                    <div className="date-label-content-creative">
                      <span className="date-label-title-creative">Дата начала занятий</span>
                      <span className="date-label-hint-creative">Выберите удобную дату из доступных</span>
                    </div>
                  </div>
                  <div className="date-picker-wrapper-creative">
                    <input
                      type="date"
                      value={selectedDate}
                      onChange={(e) => setSelectedDate(e.target.value)}
                      min={minDateStr}
                      max={maxDateStr}
                      className="date-picker-creative"
                      required
                    />
                    <div className="date-picker-accent-creative"></div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            <motion.button 
              type="submit" 
              className="submit-button-creative"
              disabled={!selectedStyle || !selectedDate}
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
            >
              <span>Записаться на занятие</span>
              <ArrowRight size={24} strokeWidth={2.5} />
              <div className="button-shine-creative"></div>
            </motion.button>

            {isSubmitted && (
              <motion.div 
                className="success-message-creative"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.3 }}
              >
                <CheckCircle size={48} strokeWidth={2.5} />
                <span>Вы успешно записаны на занятие!</span>
                <Sparkles size={24} strokeWidth={2} />
              </motion.div>
            )}
          </form>
        </motion.section>

        <ImageSlider />

        <motion.section 
          className="instructors-creative"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.8, delay: 0.5 }}
        >
          <div className="section-header-creative">
            <div className="section-brush"></div>
            <h2 className="section-title-creative">Наши преподаватели</h2>
            <div className="section-brush"></div>
          </div>
          <div className="instructors-grid">
            {[
              { name: 'Мария Иванова', specialty: 'Акварель и графика', experience: '8 лет', rating: '5.0', students: '500+' },
              { name: 'Алексей Петров', specialty: 'Графический рисунок', experience: '10 лет', rating: '5.0', students: '700+' },
              { name: 'Елена Соколова', specialty: 'Масляная живопись', experience: '12 лет', rating: '5.0', students: '600+' },
              { name: 'Дмитрий Новиков', specialty: 'Цифровое искусство', experience: '7 лет', rating: '5.0', students: '400+' }
            ].map((instructor, index) => (
              <motion.div
                key={index}
                className="instructor-card-creative"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: index * 0.05 }}
                whileHover={{ y: -4 }}
              >
                <div className="instructor-avatar-creative" style={{ background: `var(--gradient-${(index % 4) + 1})` }}>
                  <Palette size={40} strokeWidth={2.5} />
                </div>
                <h3 className="instructor-name-creative">{instructor.name}</h3>
                <div className="instructor-specialty-creative">{instructor.specialty}</div>
                <div className="instructor-stats-creative">
                  <div className="instructor-stat-creative">
                    <span className="stat-value-creative">{instructor.experience}</span>
                    <span className="stat-label-creative">Опыт</span>
                  </div>
                  <div className="instructor-stat-creative">
                    <span className="stat-value-creative">{instructor.rating}</span>
                    <span className="stat-label-creative">Рейтинг</span>
                  </div>
                  <div className="instructor-stat-creative">
                    <span className="stat-value-creative">{instructor.students}</span>
                    <span className="stat-label-creative">Учеников</span>
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        </motion.section>

      </div>
    </div>
  )
}

export default Enroll

