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, FileText, Users } 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,
      description: 'Профильная математика с углубленным изучением всех разделов',
      duration: '120 часов',
      price: 'от 15000₽'
    },
    { 
      id: 'russian', 
      name: 'Русский язык', 
      icon: BookOpen,
      description: 'Подготовка к сочинению и тестовой части',
      duration: '100 часов',
      price: 'от 12000₽'
    },
    { 
      id: 'physics', 
      name: 'Физика', 
      icon: Zap,
      description: 'Механика, термодинамика, оптика и квантовая физика',
      duration: '140 часов',
      price: 'от 18000₽'
    },
    { 
      id: 'informatics', 
      name: 'Информатика', 
      icon: Code,
      description: 'Программирование, алгоритмы и структуры данных',
      duration: '130 часов',
      price: 'от 16000₽'
    }
  ]

  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-classic">
      <div className="container">
        <motion.div 
          className="enroll-header-classic"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <h1 className="enroll-title-classic">Записаться на курс</h1>
          <div className="enroll-divider-classic"></div>
          <p className="enroll-description-classic">
            Выберите предмет и дату начала занятий. Начните подготовку к ЕГЭ 
            с опытными преподавателями и достигните высоких результатов.
          </p>
        </motion.div>

        <motion.div 
          className="enroll-form-classic"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.6, delay: 0.2 }}
        >
          <form className="form-panel-classic" onSubmit={handleSubmit}>
            <div className="form-step-classic">
              <div className="step-number-classic">1</div>
              <div className="step-content-classic">
                <div className="step-label-classic">
                  <BookOpen size={20} strokeWidth={1.5} />
                  <h2 className="step-title-classic">Выберите предмет</h2>
                </div>
                <div className="subjects-list-classic">
                  {subjects.map((subject, index) => {
                    const Icon = subject.icon
                    const isSelected = selectedSubject === subject.id
                    
                    return (
                      <motion.button
                        key={subject.id}
                        type="button"
                        className={`subject-item-classic ${isSelected ? 'selected' : ''}`}
                        onClick={() => setSelectedSubject(subject.id)}
                        initial={{ opacity: 0, x: -20 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: index * 0.1 }}
                      >
                        <div className="subject-icon-classic">
                          <Icon size={20} strokeWidth={1.5} />
                        </div>
                        <div className="subject-info-classic">
                          <h3 className="subject-name-classic">{subject.name}</h3>
                          <p className="subject-description-classic">{subject.description}</p>
                          <div className="subject-details-classic">
                            <span className="detail-item-classic">
                              <Clock size={12} strokeWidth={1.5} />
                              {subject.duration}
                            </span>
                            <span className="detail-item-classic price-classic">
                              {subject.price}
                            </span>
                          </div>
                        </div>
                        {isSelected && (
                          <motion.div
                            className="subject-check-classic"
                            initial={{ scale: 0 }}
                            animate={{ scale: 1 }}
                            transition={{ type: "spring", stiffness: 300 }}
                          >
                            <CheckCircle2 size={20} strokeWidth={1.5} />
                          </motion.div>
                        )}
                      </motion.button>
                    )
                  })}
                </div>
              </div>
            </div>

            <AnimatePresence>
              {selectedSubject && (
                <motion.div 
                  className="form-step-classic"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0 }}
                  transition={{ duration: 0.4 }}
                >
                  <div className="step-number-classic">2</div>
                  <div className="step-content-classic">
                    <div className="step-label-classic">
                      <Calendar size={20} strokeWidth={1.5} />
                      <h2 className="step-title-classic">Дата начала занятий</h2>
                    </div>
                    <div className="date-wrapper-classic">
                      <input
                        type="date"
                        value={selectedDate}
                        onChange={(e) => setSelectedDate(e.target.value)}
                        min={minDateStr}
                        max={maxDateStr}
                        className="date-input-classic"
                        required
                      />
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            <motion.button 
              type="submit" 
              className="submit-button-classic"
              disabled={!selectedSubject || !selectedDate}
              whileHover={{ scale: 1.01 }}
              whileTap={{ scale: 0.99 }}
            >
              <span>Записаться на курс</span>
              <ArrowRight size={18} strokeWidth={1.5} />
            </motion.button>

            {isSubmitted && (
              <motion.div 
                className="success-classic"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.3 }}
              >
                <CheckCircle2 size={28} strokeWidth={1.5} />
                <span>Вы успешно записались на курс!</span>
              </motion.div>
            )}
          </form>
        </motion.div>

        <motion.div 
          className="advantages-panel-classic"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.4 }}
        >
          <div className="panel-header-classic">
            <h2 className="panel-title-classic">Преимущества обучения</h2>
            <div className="panel-divider-classic"></div>
          </div>
          <div className="advantages-list-classic">
            {[
              { icon: Users, title: 'Опытные преподаватели', text: 'Преподаватели с многолетним опытом работы и глубоким знанием предмета' },
              { icon: FileText, title: 'Системная подготовка', text: 'Поэтапное изучение материала с регулярным контролем знаний' },
              { icon: Clock, title: 'Гибкий график', text: 'Возможность выбрать удобное время для занятий' },
              { icon: Zap, title: 'Индивидуальный подход', text: 'Персональная программа обучения для каждого ученика' }
            ].map((advantage, index) => (
              <motion.div
                key={index}
                className="advantage-item-classic"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.5 + index * 0.1 }}
              >
                <div className="advantage-icon-classic">
                  <advantage.icon size={24} strokeWidth={1.5} />
                </div>
                <h3 className="advantage-title-classic">{advantage.title}</h3>
                <p className="advantage-text-classic">{advantage.text}</p>
              </motion.div>
            ))}
          </div>
        </motion.div>

        <motion.div 
          className="testimonials-panel-classic"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.6 }}
        >
          <div className="panel-header-classic">
            <h2 className="panel-title-classic">Отзывы учеников</h2>
            <div className="panel-divider-classic"></div>
          </div>
          <div className="testimonials-list-classic">
            {[
              { name: 'Анна Иванова', subject: 'Математика', score: 92, text: 'Отличная подготовка! Преподаватель объясняет очень понятно, все темы разобраны детально.' },
              { name: 'Дмитрий Петров', subject: 'Физика', score: 88, text: 'Благодаря курсу смог систематизировать знания и успешно сдать экзамен.' },
              { name: 'Мария Соколова', subject: 'Русский язык', score: 95, text: 'Очень довольна результатом. Особенно помогло в подготовке к сочинению.' }
            ].map((testimonial, index) => (
              <motion.div
                key={index}
                className="testimonial-item-classic"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.7 + index * 0.1 }}
              >
                <div className="testimonial-header-classic">
                  <div className="testimonial-name-classic">{testimonial.name}</div>
                  <div className="testimonial-score-classic">{testimonial.score} баллов</div>
                </div>
                <div className="testimonial-subject-classic">{testimonial.subject}</div>
                <p className="testimonial-text-classic">"{testimonial.text}"</p>
              </motion.div>
            ))}
          </div>
        </motion.div>
      </div>
    </div>
  )
}

export default Enroll
