import { useState, useRef, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Megaphone, Mail, BarChart3, Target, Calendar, CheckCircle, Briefcase, DollarSign, TrendingUp, Users, ArrowRight, Sparkles } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './Enroll.css'

const Enroll = () => {
  const navigate = useNavigate()
  const [selectedDirection, setSelectedDirection] = useState('')
  const [startDate, setStartDate] = useState('')
  const [isSubmitted, setIsSubmitted] = useState(false)

  const directions = [
    { 
      id: 'smm', 
      name: 'SMM', 
      icon: Megaphone,
      color: '#FF006E',
      gradient: 'linear-gradient(135deg, #FF006E 0%, #FF6B35 100%)',
      description: 'Социальные сети и контент-маркетинг. Научитесь создавать вирусный контент и управлять сообществами.',
      duration: '8 недель',
      students: '1200+',
      rating: '4.9'
    },
    { 
      id: 'email', 
      name: 'Email-маркетинг', 
      icon: Mail,
      color: '#FF6B35',
      gradient: 'linear-gradient(135deg, #FF6B35 0%, #FFBE0B 100%)',
      description: 'Эффективные email-рассылки и автоматизация. Повышайте конверсию с помощью персонализированных писем.',
      duration: '6 недель',
      students: '800+',
      rating: '4.8'
    },
    { 
      id: 'analytics', 
      name: 'Аналитика', 
      icon: BarChart3,
      color: '#06FFA5',
      gradient: 'linear-gradient(135deg, #06FFA5 0%, #8338EC 100%)',
      description: 'Работа с данными и метриками. Научитесь анализировать эффективность маркетинговых кампаний.',
      duration: '10 недель',
      students: '950+',
      rating: '4.9'
    },
    { 
      id: 'context', 
      name: 'Контекстная реклама', 
      icon: Target,
      color: '#8338EC',
      gradient: 'linear-gradient(135deg, #8338EC 0%, #FF006E 100%)',
      description: 'Яндекс.Директ и Google Ads. Создавайте эффективные рекламные кампании и оптимизируйте бюджет.',
      duration: '8 недель',
      students: '1100+',
      rating: '4.8'
    }
  ]

  const handleSubmit = (e) => {
    e.preventDefault()
    
    if (!selectedDirection || !startDate) {
      alert('Пожалуйста, выберите направление и дату старта')
      return
    }

    const saved = localStorage.getItem('marketingCourses')
    const courses = saved ? JSON.parse(saved) : []
    
    const directionData = directions.find(d => d.id === selectedDirection)
    
    const newCourse = {
      id: Date.now(),
      module: directionData.name,
      mentor: 'Преподаватель будет назначен',
      startDate: startDate,
      status: 'active',
      certificate: null,
      grade: null
    }
    
    courses.push(newCourse)
    localStorage.setItem('marketingCourses', JSON.stringify(courses))
    
    setIsSubmitted(true)
    
    setTimeout(() => {
      navigate('/')
    }, 2000)
  }

  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]

  return (
    <div className="enroll-page-creative">
      <div className="container">
        <section className="enroll-header-creative">
          <div className="header-badge-creative">
            <Target size={20} />
            <span>ЗАПИСЬ НА КУРС</span>
          </div>
          <h1 className="enroll-title-creative">
            Записаться на <span className="title-accent-creative">курс</span>
          </h1>
          <p className="enroll-description-creative">
            Выберите направление и дату старта. Все курсы включают практические задания и обратную связь от наставников.
          </p>
        </section>

        <section className="enroll-form-section-creative">
          <form className="form-creative" onSubmit={handleSubmit}>
            <div className="directions-selection-creative">
              {directions.map((direction) => {
                const Icon = direction.icon
                return (
                  <button
                    key={direction.id}
                    type="button"
                    className={`direction-card-creative ${selectedDirection === direction.id ? 'selected' : ''}`}
                    onClick={() => setSelectedDirection(direction.id)}
                    style={{ 
                      '--direction-color': direction.color,
                      background: selectedDirection === direction.id ? direction.gradient : 'var(--bg-card)'
                    }}
                  >
                    <div className="direction-icon-wrapper-creative">
                      <Icon size={40} />
                    </div>
                    <h3 className="direction-name-creative">{direction.name}</h3>
                    <p className="direction-desc-creative">{direction.description}</p>
                    <div className="direction-stats-creative">
                      <div className="direction-stat-creative">
                        <span className="stat-label-creative">Длительность:</span>
                        <span className="stat-value-creative">{direction.duration}</span>
                      </div>
                      <div className="direction-stat-creative">
                        <span className="stat-label-creative">Студентов:</span>
                        <span className="stat-value-creative">{direction.students}</span>
                      </div>
                      <div className="direction-stat-creative">
                        <span className="stat-label-creative">Рейтинг:</span>
                        <span className="stat-value-creative">{direction.rating}</span>
                      </div>
                    </div>
                    {selectedDirection === direction.id && (
                      <div className="check-badge-creative">
                        <CheckCircle size={24} />
                      </div>
                    )}
                  </button>
                )
              })}
            </div>

            {selectedDirection && (
              <div className="date-section-creative">
                <div className="date-label-creative">
                  <Calendar size={20} />
                  <span>Дата старта курса</span>
                </div>
                <input
                  type="date"
                  className="date-input-creative"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  min={minDateStr}
                  max={maxDateStr}
                  required
                />
              </div>
            )}

            <button 
              type="submit" 
              className="submit-btn-creative" 
              disabled={!selectedDirection || !startDate || isSubmitted}
            >
              <span>Записаться на курс</span>
            </button>

            {isSubmitted && (
              <div className="success-message-creative">
                <CheckCircle size={32} />
                <span>Запись успешно оформлена!</span>
              </div>
            )}
          </form>
        </section>

        <ImageSlider />
      </div>
    </div>
  )
}

export default Enroll

