import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { BookOpen, User, BarChart3, FileText, Calendar, Clock, ChevronRight } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './MyCourses.css'

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

  useEffect(() => {
    const saved = localStorage.getItem('egeCourses')
    if (saved) {
      try {
        setCourses(JSON.parse(saved))
      } catch (e) {
        setCourses([])
      }
    } else {
      const defaultCourses = [
        {
          id: 1,
          subject: 'Математика',
          instructor: 'Александр Петров',
          progress: 75,
          testResults: [
            { name: 'Пробный ЕГЭ №1', score: 82, maxScore: 100, date: '2025-04-10' },
            { name: 'Пробный ЕГЭ №2', score: 88, maxScore: 100, date: '2025-04-17' }
          ]
        },
        {
          id: 2,
          subject: 'Русский язык',
          instructor: 'Елена Соколова',
          progress: 60,
          testResults: [
            { name: 'Пробный ЕГЭ №1', score: 90, maxScore: 100, date: '2025-04-12' }
          ]
        },
        {
          id: 3,
          subject: 'Физика',
          instructor: 'Дмитрий Новиков',
          progress: 45,
          testResults: []
        }
      ]
      setCourses(defaultCourses)
      localStorage.setItem('egeCourses', JSON.stringify(defaultCourses))
    }
  }, [])

  const totalCourses = courses.length
  const totalProgress = courses.length > 0
    ? Math.round(courses.reduce((sum, c) => sum + c.progress, 0) / courses.length)
    : 0

  const allTests = courses.flatMap(c => c.testResults)
  const averageScore = allTests.length > 0
    ? Math.round(allTests.reduce((sum, t) => sum + (t.score / t.maxScore) * 100, 0) / allTests.length)
    : 0

  return (
    <div className="my-courses-classic">
      <div className="container">
        <motion.div 
          className="page-header-classic"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <div className="header-top">
            <h1 className="page-title-classic">Мои курсы</h1>
            <div className="header-meta">
              <span className="meta-item-classic">
                <BookOpen size={16} strokeWidth={1.5} />
                {totalCourses} курсов
              </span>
              <span className="meta-item-classic">
                <BarChart3 size={16} strokeWidth={1.5} />
                {totalProgress}% прогресс
              </span>
            </div>
          </div>
          <div className="header-divider-classic"></div>
          <p className="page-description-classic">
            Отслеживайте свой прогресс в изучении предметов, анализируйте результаты 
            пробных экзаменов и продолжайте подготовку к ЕГЭ.
          </p>
        </motion.div>

        <motion.div 
          className="stats-panel-classic"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.2 }}
        >
          <div className="stat-panel-item">
            <div className="stat-panel-label">Курсов</div>
            <div className="stat-panel-value">{totalCourses}</div>
          </div>
          <div className="stat-panel-divider"></div>
          <div className="stat-panel-item">
            <div className="stat-panel-label">Прогресс</div>
            <div className="stat-panel-value">{totalProgress}%</div>
          </div>
          <div className="stat-panel-divider"></div>
          <div className="stat-panel-item">
            <div className="stat-panel-label">Средний балл</div>
            <div className="stat-panel-value">{averageScore}</div>
          </div>
          <div className="stat-panel-divider"></div>
          <div className="stat-panel-item">
            <div className="stat-panel-label">Тестов</div>
            <div className="stat-panel-value">{allTests.length}</div>
          </div>
        </motion.div>

        <ImageSlider />

        <motion.div 
          className="courses-panel-classic"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.6, delay: 0.4 }}
        >
          {courses.length === 0 ? (
            <div className="empty-panel-classic">
              <div className="empty-icon-classic">
                <BookOpen size={40} strokeWidth={1.5} />
              </div>
              <h3 className="empty-title-classic">Начните обучение</h3>
              <p className="empty-text-classic">
                Запишитесь на первый курс и начните подготовку к ЕГЭ
              </p>
            </div>
          ) : (
            <div className="courses-stack-classic">
              {courses.map((course, index) => {
                const date = new Date()
                const formattedDate = date.toLocaleDateString('ru-RU', { 
                  day: 'numeric', 
                  month: 'long',
                  year: 'numeric'
                })
                
                return (
                  <motion.div
                    key={course.id}
                    className="course-panel-classic"
                    initial={{ opacity: 0, x: -30 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: 0.5 + index * 0.1 }}
                  >
                    <div className="panel-header-classic">
                      <div className="panel-subject-classic">{course.subject}</div>
                      <div className="panel-progress-classic">{course.progress}%</div>
                    </div>
                    <div className="panel-body-classic">
                      <div className="panel-instructor-classic">
                        <User size={14} strokeWidth={1.5} />
                        <span>{course.instructor}</span>
                      </div>
                      <div className="panel-progress-track-classic">
                        <motion.div 
                          className="panel-progress-fill-classic"
                          initial={{ width: 0 }}
                          animate={{ width: `${course.progress}%` }}
                          transition={{ duration: 0.8, delay: 0.6 + index * 0.1 }}
                        />
                      </div>
                    </div>
                    {course.testResults.length > 0 && (
                      <div className="panel-tests-classic">
                        <div className="tests-label-classic">
                          <FileText size={14} strokeWidth={1.5} />
                          <span>Результаты тестов</span>
                        </div>
                        <div className="tests-stack-classic">
                          {course.testResults.map((test, i) => {
                            const testDate = new Date(test.date)
                            const formattedTestDate = testDate.toLocaleDateString('ru-RU', { 
                              day: 'numeric', 
                              month: 'short'
                            })
                            
                            return (
                              <div key={i} className="test-panel-classic">
                                <div className="test-info-classic">
                                  <div className="test-name-classic">{test.name}</div>
                                  <div className="test-date-classic">
                                    <Calendar size={12} strokeWidth={1.5} />
                                    {formattedTestDate}
                                  </div>
                                </div>
                                <div className="test-score-classic">
                                  <span className="score-main-classic">{test.score}</span>
                                  <span className="score-separator-classic">/</span>
                                  <span className="score-max-classic">{test.maxScore}</span>
                                </div>
                              </div>
                            )
                          })}
                        </div>
                      </div>
                    )}
                    <div className="panel-footer-classic">
                      <span className="panel-action-classic">
                        Подробнее
                        <ChevronRight size={14} strokeWidth={1.5} />
                      </span>
                    </div>
                  </motion.div>
                )
              })}
            </div>
          )}
        </motion.div>

        <motion.div 
          className="info-panel-classic"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.6 }}
        >
          <div className="info-header-classic">
            <h2 className="info-title-classic">Методика обучения</h2>
            <div className="info-divider-classic"></div>
          </div>
          <div className="info-content-classic">
            <div className="info-item-classic">
              <h3 className="info-item-title-classic">Системный подход</h3>
              <p className="info-item-text-classic">
                Поэтапное изучение материала от основ к сложным темам, 
                с регулярным контролем знаний и корректировкой программы обучения.
              </p>
            </div>
            <div className="info-item-classic">
              <h3 className="info-item-title-classic">Индивидуальная работа</h3>
              <p className="info-item-text-classic">
                Персональный подход к каждому ученику с учетом его уровня подготовки 
                и особенностей восприятия материала.
              </p>
            </div>
            <div className="info-item-classic">
              <h3 className="info-item-title-classic">Практическая направленность</h3>
              <p className="info-item-text-classic">
                Большое количество практических заданий и пробных экзаменов 
                для закрепления материала и подготовки к формату ЕГЭ.
              </p>
            </div>
          </div>
        </motion.div>
      </div>
    </div>
  )
}

export default MyCourses
