import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { BookOpen, User, Award, Star, Package, CheckCircle, BarChart3, TrendingUp, Target, Users, Zap, ArrowRight } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './MyCourses.css'

const MyCourses = () => {
  const navigate = useNavigate()
  const [courses, setCourses] = useState([])

  useEffect(() => {
    const saved = localStorage.getItem('marketingCourses')
    const defaultCourses = [
      {
        id: 1,
        module: 'Основы SMM',
        mentor: 'Анна Петрова',
        startDate: '2025-05-15',
        status: 'active',
        certificate: null,
        grade: null
      },
      {
        id: 2,
        module: 'Email-маркетинг',
        mentor: 'Дмитрий Соколов',
        startDate: '2025-04-20',
        status: 'completed',
        certificate: 'Сертификат выдан',
        grade: 5
      },
      {
        id: 3,
        module: 'Аналитика данных',
        mentor: 'Мария Волкова',
        startDate: '2025-03-10',
        status: 'completed',
        certificate: null,
        grade: 4
      }
    ]
    
    if (saved) {
      try {
        const parsed = JSON.parse(saved)
        const validCourses = parsed.filter(course => 
          course.module && course.mentor && course.startDate &&
          course.startDate.match(/^\d{4}-\d{2}-\d{2}$/)
        )
        if (validCourses.length > 0) {
          setCourses(parsed)
        } else {
          setCourses(defaultCourses)
          localStorage.setItem('marketingCourses', JSON.stringify(defaultCourses))
        }
      } catch (e) {
        setCourses(defaultCourses)
        localStorage.setItem('marketingCourses', JSON.stringify(defaultCourses))
      }
    } else {
      setCourses(defaultCourses)
      localStorage.setItem('marketingCourses', JSON.stringify(defaultCourses))
    }
  }, [])

  const formatDate = (dateString) => {
    if (!dateString) return 'Не указано'
    try {
      const [year, month, day] = dateString.split('-').map(Number)
      if (!year || !month || !day) return 'Не указано'
      
      const date = new Date(year, month - 1, day)
      if (isNaN(date.getTime())) return 'Не указано'
      
      return date.toLocaleDateString('ru-RU', { 
        day: 'numeric', 
        month: 'long', 
        year: 'numeric' 
      })
    } catch (e) {
      return 'Не указано'
    }
  }

  return (
    <div className="my-courses-page-marketing">
      <div className="container">
        <section className="page-header-marketing">
          <div className="header-badge-marketing">
            <BarChart3 size={20} />
            <span>ВАШИ КУРСЫ</span>
          </div>
          <h1 className="page-title-marketing">
            Мои <span className="title-accent-marketing">курсы</span>
          </h1>
          <p className="page-description-marketing">
            Отслеживайте прогресс обучения, общайтесь с наставниками и получайте сертификаты
          </p>
        </section>

        <ImageSlider />

        <AchievementsSection />

        <PopularModulesSection />

        {courses.length === 0 ? (
          <div className="empty-state-marketing">
            <div className="empty-icon-wrapper-marketing">
              <Package size={64} />
            </div>
            <h2 className="empty-title-marketing">Нет курсов</h2>
            <p className="empty-text-marketing">Запишитесь на первый курс по маркетингу</p>
            <button 
              className="empty-button-marketing" 
              onClick={() => navigate('/enroll')}
            >
              Записаться на курс
            </button>
          </div>
        ) : (
          <section className="courses-list-marketing">
            <div className="courses-grid-marketing">
              {courses.map((course) => (
                <CourseCard
                  key={course.id}
                  course={course}
                  formatDate={formatDate}
                />
              ))}
            </div>
          </section>
        )}
      </div>
    </div>
  )
}

const CourseCard = ({ course, formatDate }) => {
  return (
    <div className={`course-item-marketing ${course.status}`}>
      <div className="course-header-marketing">
        <div className="course-icon-wrapper-marketing">
          <BookOpen size={32} />
        </div>
        <div className="course-info-marketing">
          <div className="course-number-marketing">#{course.id}</div>
          <div className={`status-badge-marketing ${course.status}`}>
            {course.status === 'active' ? (
              <>
                <CheckCircle size={16} />
                <span>Активен</span>
              </>
            ) : (
              <>
                <Award size={16} />
                <span>Завершен</span>
              </>
            )}
          </div>
        </div>
      </div>
      
      <h3 className="course-title-marketing">{course.module}</h3>
      
      <div className="course-details-marketing">
        <div className="detail-item-marketing">
          <User size={18} />
          <div>
            <span className="detail-label-marketing">Наставник:</span>
            <span className="detail-value-marketing">{course.mentor}</span>
          </div>
        </div>
        <div className="detail-item-marketing">
          <BarChart3 size={18} />
          <div>
            <span className="detail-label-marketing">Старт:</span>
            <span className="detail-value-marketing">{formatDate(course.startDate)}</span>
          </div>
        </div>
      </div>
      
      {course.status === 'completed' && (
        <div className="course-results-marketing">
          {course.certificate && (
            <div className="certificate-badge-marketing">
              <Award size={20} />
              <span>{course.certificate}</span>
            </div>
          )}
          {course.grade && (
            <div className="grade-badge-marketing">
              <div className="grade-stars-marketing">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Star
                    key={i}
                    size={20}
                    fill={i < course.grade ? '#F59E0B' : 'none'}
                    color={i < course.grade ? '#F59E0B' : '#475569'}
                  />
                ))}
              </div>
              <span className="grade-value-marketing">Оценка: {course.grade}/5</span>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

const AchievementsSection = () => {
  const sectionRef = useRef(null)
  const [isVisible, setIsVisible] = useState(false)
  const [counters, setCounters] = useState({ students: 0, courses: 0, certificates: 0 })

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true)
        }
      },
      { threshold: 0.1 }
    )

    if (sectionRef.current) {
      observer.observe(sectionRef.current)
    }

    return () => {
      if (sectionRef.current) {
        observer.unobserve(sectionRef.current)
      }
    }
  }, [])

  useEffect(() => {
    if (isVisible) {
      const duration = 2000
      const steps = 60
      const stepTime = duration / steps
      
      const animate = (key, target) => {
        let current = 0
        const increment = target / steps
        const timer = setInterval(() => {
          current += increment
          if (current >= target) {
            current = target
            clearInterval(timer)
          }
          setCounters(prev => ({ ...prev, [key]: Math.floor(current) }))
        }, stepTime)
      }

      animate('students', 5000)
      animate('courses', 120)
      animate('certificates', 3500)
    }
  }, [isVisible])

  const achievements = [
    {
      icon: Users,
      value: `${counters.students}+`,
      label: 'Студентов обучается',
      color: 'var(--marketing-blue-light)'
    },
    {
      icon: BookOpen,
      value: `${counters.courses}+`,
      label: 'Активных курсов',
      color: 'var(--marketing-purple-light)'
    },
    {
      icon: Award,
      value: `${counters.certificates}+`,
      label: 'Выдано сертификатов',
      color: 'var(--marketing-cyan)'
    }
  ]

  return (
    <section 
      ref={sectionRef}
      className={`achievements-section-marketing ${isVisible ? 'visible' : ''}`}
    >
      <div className="container">
        <div className="achievements-header-marketing">
          <h2 className="achievements-title-marketing">Наши достижения</h2>
          <p className="achievements-description-marketing">
            Тысячи специалистов уже прошли обучение и получили новые навыки
          </p>
        </div>
        <div className="achievements-grid-marketing">
          {achievements.map((achievement, index) => {
            const Icon = achievement.icon
            return (
              <div 
                key={index} 
                className="achievement-card-marketing"
                style={{ 
                  animationDelay: `${index * 0.1}s`,
                  '--achievement-color': achievement.color
                }}
              >
                <div className="achievement-icon-wrapper-marketing">
                  <Icon size={36} />
                </div>
                <div className="achievement-value-marketing">{achievement.value}</div>
                <div className="achievement-label-marketing">{achievement.label}</div>
              </div>
            )
          })}
        </div>
      </div>
    </section>
  )
}

const PopularModulesSection = () => {
  const sectionRef = useRef(null)
  const [isVisible, setIsVisible] = useState(false)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true)
        }
      },
      { threshold: 0.1 }
    )

    if (sectionRef.current) {
      observer.observe(sectionRef.current)
    }

    return () => {
      if (sectionRef.current) {
        observer.unobserve(sectionRef.current)
      }
    }
  }, [])

  const modules = [
    {
      icon: Target,
      title: 'Стратегия маркетинга',
      description: 'Построение маркетинговой стратегии и планирование кампаний',
      students: '850+',
      color: 'var(--marketing-blue)'
    },
    {
      icon: TrendingUp,
      title: 'Рост и масштабирование',
      description: 'Инструменты для роста бизнеса и масштабирования маркетинга',
      students: '720+',
      color: 'var(--marketing-purple)'
    },
    {
      icon: Zap,
      title: 'Автоматизация',
      description: 'Внедрение автоматизации в маркетинговые процессы',
      students: '680+',
      color: 'var(--marketing-cyan)'
    }
  ]

  return (
    <section 
      ref={sectionRef}
      className={`popular-modules-section-marketing ${isVisible ? 'visible' : ''}`}
    >
      <div className="container">
        <div className="popular-modules-header-marketing">
          <h2 className="popular-modules-title-marketing">Популярные модули</h2>
          <p className="popular-modules-description-marketing">
            Самые востребованные направления обучения
          </p>
        </div>
        <div className="popular-modules-grid-marketing">
          {modules.map((module, index) => {
            const Icon = module.icon
            return (
              <div 
                key={index} 
                className="module-card-marketing"
                style={{ 
                  animationDelay: `${index * 0.15}s`,
                  '--module-color': module.color
                }}
              >
                <div className="module-icon-wrapper-marketing">
                  <Icon size={40} />
                </div>
                <h3 className="module-title-marketing">{module.title}</h3>
                <p className="module-text-marketing">{module.description}</p>
                <div className="module-stats-marketing">
                  <Users size={16} />
                  <span>{module.students} студентов</span>
                </div>
                <div className="module-link-marketing">
                  <span>Узнать больше</span>
                  <ArrowRight size={16} />
                </div>
              </div>
            )
          })}
        </div>
      </div>
    </section>
  )
}

export default MyCourses

