import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion, AnimatePresence } from 'framer-motion'
import { Calendar, Calculator, BookOpen, Code, Zap, Clock, CheckCircle2, ArrowRight, Sparkles, TrendingUp, Users, Award } from 'lucide-react'
import './Enroll.css'

const Enroll = () => {
  const navigate = useNavigate()
  const [selectedSubject, setSelectedSubject] = useState('')
  const [selectedDate, setSelectedDate] = useState('')
  const [isSubmitted, setIsSubmitted] = useState(false)

  const subjects = [
    { 
      id: 'math', 
      name: 'Математика', 
      icon: Calculator,
      gradient: 'linear-gradient(135deg, #667EEA 0%, #764BA2 100%)',
      description: 'Профильная математика с углубленным изучением всех разделов',
      duration: '120 часов',
      price: 'от 15000₽',
      stats: { students: '1200+', success: '94%' }
    },
    { 
      id: 'russian', 
      name: 'Русский язык', 
      icon: BookOpen,
      gradient: 'linear-gradient(135deg, #F093FB 0%, #F5576C 100%)',
      description: 'Подготовка к сочинению и тестовой части',
      duration: '100 часов',
      price: 'от 12000₽',
      stats: { students: '980+', success: '96%' }
    },
    { 
      id: 'physics', 
      name: 'Физика', 
      icon: Zap,
      gradient: 'linear-gradient(135deg, #4FACFE 0%, #00F2FE 100%)',
      description: 'Механика, термодинамика, оптика и квантовая физика',
      duration: '140 часов',
      price: 'от 18000₽',
      stats: { students: '750+', success: '92%' }
    },
    { 
      id: 'informatics', 
      name: 'Информатика', 
      icon: Code,
      gradient: 'linear-gradient(135deg, #43E97B 0%, #38F9D7 100%)',
      description: 'Программирование, алгоритмы и структуры данных',
      duration: '130 часов',
      price: 'от 16000₽',
      stats: { students: '650+', success: '91%' }
    }
  ]

  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 (!selectedSubject || !selectedDate) return

    const saved = localStorage.getItem('egeCourses')
    const courses = saved ? JSON.parse(saved) : []
    
    const subjectData = subjects.find(s => s.id === selectedSubject)
    
    const newCourse = {
      id: Date.now(),
      subject: subjectData.name,
      instructor: 'Преподаватель',
      progress: 0,
      testResults: []
    }
    
    courses.push(newCourse)
    localStorage.setItem('egeCourses', JSON.stringify(courses))
    
    setIsSubmitted(true)
    setTimeout(() => {
      navigate('/')
    }, 2000)
  }

  return (
    <div className="enroll-page">
      <div className="container">
        <motion.div 
          className="enroll-hero-modern"
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <div className="hero-badge-modern">
            <Sparkles size={18} strokeWidth={2.5} />
            <span>НАЧНИТЕ СЕГОДНЯ</span>
          </div>
          <h1 className="hero-title-modern">
            Выберите курс <span className="title-accent">подготовки</span>
          </h1>
          <p className="hero-description-modern">
            Индивидуальный подход, опытные преподаватели и гарантированный результат. 
            Начните подготовку к ЕГЭ уже сегодня.
          </p>
        </motion.div>

        <motion.div 
          className="enroll-form-modern"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.6, delay: 0.2 }}
        >
          <form className="form-container-modern" onSubmit={handleSubmit}>
            <div className="form-step">
              <div className="step-indicator">
                <div className={`step-dot ${selectedSubject ? 'completed' : 'active'}`}>
                  {selectedSubject ? <CheckCircle2 size={20} strokeWidth={2.5} /> : '1'}
                </div>
                <div className="step-line">
                  <motion.div 
                    className="step-line-fill"
                    initial={{ width: 0 }}
                    animate={{ width: selectedSubject ? '100%' : '0%' }}
                    transition={{ duration: 0.5 }}
                  />
                </div>
                <div className={`step-dot ${selectedDate ? 'completed' : selectedSubject ? 'active' : ''}`}>
                  {selectedDate ? <CheckCircle2 size={20} strokeWidth={2.5} /> : '2'}
                </div>
              </div>

              <div className="form-section">
                <div className="section-label-modern">
                  <h2 className="label-title-modern">Выберите предмет</h2>
                  <p className="label-hint-modern">Выберите предмет для подготовки к ЕГЭ</p>
                </div>
                <div className="subjects-showcase">
                  {subjects.map((subject, index) => {
                    const Icon = subject.icon
                    const isSelected = selectedSubject === subject.id
                    
                    return (
                      <motion.button
                        key={subject.id}
                        type="button"
                        className={`subject-showcase-card ${isSelected ? 'selected' : ''}`}
                        onClick={() => setSelectedSubject(subject.id)}
                        initial={{ opacity: 0, y: 30 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: index * 0.1 }}
                        whileHover={{ scale: 1.05, y: -8 }}
                        whileTap={{ scale: 0.98 }}
                        style={{
                          background: isSelected ? subject.gradient : 'white',
                          borderColor: isSelected ? 'transparent' : '#E2E8F0'
                        }}
                      >
                        <div className="showcase-icon-wrapper">
                          <div 
                            className="showcase-icon"
                            style={{
                              background: isSelected ? 'rgba(255, 255, 255, 0.25)' : `${subject.gradient}15`,
                              borderColor: isSelected ? 'rgba(255, 255, 255, 0.4)' : 'transparent'
                            }}
                          >
                            <Icon 
                              size={48} 
                              strokeWidth={2.5}
                              style={{ color: isSelected ? 'white' : '#667EEA' }}
                            />
                          </div>
                          {isSelected && (
                            <motion.div
                              className="showcase-check"
                              initial={{ scale: 0, rotate: -180 }}
                              animate={{ scale: 1, rotate: 0 }}
                              transition={{ type: "spring", stiffness: 300 }}
                            >
                              <CheckCircle2 size={32} strokeWidth={2.5} />
                            </motion.div>
                          )}
                        </div>
                        <div className="showcase-content">
                          <h3 
                            className="showcase-name"
                            style={{ color: isSelected ? 'white' : '#1E293B' }}
                          >
                            {subject.name}
                          </h3>
                          <p 
                            className="showcase-description"
                            style={{ color: isSelected ? 'rgba(255, 255, 255, 0.9)' : '#64748B' }}
                          >
                            {subject.description}
                          </p>
                          <div className="showcase-stats">
                            <div className="stat-item-modern">
                              <Users size={16} strokeWidth={2} />
                              <span>{subject.stats.students}</span>
                            </div>
                            <div className="stat-item-modern">
                              <TrendingUp size={16} strokeWidth={2} />
                              <span>{subject.stats.success}</span>
                            </div>
                          </div>
                          <div className="showcase-meta">
                            <div className="meta-item-modern">
                              <Clock size={16} strokeWidth={2} />
                              <span>{subject.duration}</span>
                            </div>
                            <div className="meta-item-modern price">
                              <span>{subject.price}</span>
                            </div>
                          </div>
                        </div>
                      </motion.button>
                    )
                  })}
                </div>
              </div>

              <AnimatePresence>
                {selectedSubject && (
                  <motion.div 
                    className="form-section date-section-modern"
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    transition={{ duration: 0.4 }}
                  >
                    <div className="section-label-modern">
                      <h2 className="label-title-modern">Дата начала</h2>
                      <p className="label-hint-modern">Выберите удобную дату для начала занятий</p>
                    </div>
                    <div className="date-picker-modern">
                      <Calendar size={24} strokeWidth={2} className="date-icon" />
                      <input
                        type="date"
                        value={selectedDate}
                        onChange={(e) => setSelectedDate(e.target.value)}
                        min={minDateStr}
                        max={maxDateStr}
                        className="date-input-modern"
                        required
                      />
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>

              <motion.button 
                type="submit" 
                className="submit-button-modern"
                disabled={!selectedSubject || !selectedDate}
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <span>Записаться на курс</span>
                <ArrowRight size={24} strokeWidth={2.5} />
              </motion.button>

              {isSubmitted && (
                <motion.div 
                  className="success-modern"
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ type: "spring", stiffness: 300 }}
                >
                  <CheckCircle2 size={40} strokeWidth={2.5} />
                  <span>Вы успешно записались на курс!</span>
                </motion.div>
              )}
            </div>
          </form>
        </motion.div>

        <motion.div 
          className="features-modern"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.4 }}
        >
          <div className="features-header">
            <h2 className="features-title">Почему выбирают нас</h2>
          </div>
          <div className="features-grid-modern">
            {[
              { icon: Users, title: 'Опытные преподаватели', text: 'Преподаватели с опытом работы более 10 лет и глубоким знанием предмета' },
              { icon: Award, title: 'Высокие результаты', text: '95% наших учеников успешно сдают ЕГЭ на 80+ баллов' },
              { icon: TrendingUp, title: 'Индивидуальный подход', text: 'Персональная программа обучения для каждого ученика' },
              { icon: Zap, title: 'Гибкий график', text: 'Занятия в удобное для вас время, онлайн и офлайн форматы' }
            ].map((feature, index) => (
              <motion.div
                key={index}
                className="feature-card-modern"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.5 + index * 0.1 }}
                whileHover={{ y: -8, boxShadow: '0 16px 32px rgba(102, 126, 234, 0.2)' }}
              >
                <div className="feature-icon-modern">
                  <feature.icon size={32} strokeWidth={2.5} />
                </div>
                <h3 className="feature-title-modern">{feature.title}</h3>
                <p className="feature-text-modern">{feature.text}</p>
              </motion.div>
            ))}
          </div>
        </motion.div>

        <motion.div 
          className="cta-modern"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.6 }}
        >
          <div className="cta-content">
            <h2 className="cta-title">Готовы начать?</h2>
            <p className="cta-text">Присоединяйтесь к тысячам успешных выпускников</p>
            <div className="cta-stats">
              <div className="cta-stat">
                <div className="cta-stat-value">5000+</div>
                <div className="cta-stat-label">Учеников</div>
              </div>
              <div className="cta-stat">
                <div className="cta-stat-value">95%</div>
                <div className="cta-stat-label">Сдают на 80+</div>
              </div>
              <div className="cta-stat">
                <div className="cta-stat-value">4.9</div>
                <div className="cta-stat-label">Рейтинг</div>
              </div>
            </div>
          </div>
        </motion.div>
      </div>
    </div>
  )
}

export default Enroll
