import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { PenTool, User, Calendar, Star, BookOpen, Award } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './MyLessons.css'

const MyLessons = () => {
  const [lessons, setLessons] = useState([])

  useEffect(() => {
    const saved = localStorage.getItem('drawingLessons')
    if (saved) {
      try {
        setLessons(JSON.parse(saved))
      } catch (e) {
        setLessons([])
      }
    } else {
      const defaultLessons = [
        {
          id: 1,
          technique: 'Акварельная живопись',
          instructor: 'Мария Иванова',
          date: '2025-04-15',
          rating: 5,
          workTitle: 'Пейзаж с озером'
        },
        {
          id: 2,
          technique: 'Графический рисунок',
          instructor: 'Алексей Петров',
          date: '2025-04-12',
          rating: 4,
          workTitle: 'Портрет в карандаше'
        },
        {
          id: 3,
          technique: 'Масляная живопись',
          instructor: 'Елена Соколова',
          date: '2025-04-10',
          rating: 5,
          workTitle: 'Натюрморт с фруктами'
        }
      ]
      setLessons(defaultLessons)
      localStorage.setItem('drawingLessons', JSON.stringify(defaultLessons))
    }
  }, [])

  const totalLessons = lessons.length
  const averageRating = lessons.length > 0
    ? (lessons.reduce((sum, l) => sum + l.rating, 0) / lessons.length).toFixed(1)
    : 0
  const upcomingLessons = lessons.filter(l => new Date(l.date) >= new Date()).length
  const completedLessons = lessons.filter(l => new Date(l.date) < new Date()).length

  return (
    <div className="my-lessons">
      <div className="container">
        <motion.section 
          className="hero-elegant"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <div className="hero-content-elegant">
            <h1 className="hero-title-elegant">Мои занятия</h1>
            <div className="hero-divider"></div>
            <p className="hero-description-elegant">
              Отслеживайте свой творческий путь. Каждое занятие — это шаг к мастерству, 
              каждая работа — отражение вашего роста как художника.
            </p>
          </div>
        </motion.section>

        <motion.section 
          className="stats-elegant"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.2 }}
        >
          <div className="stats-elegant-list">
            <div className="stat-elegant-item">
              <div className="stat-elegant-icon">
                <BookOpen size={22} strokeWidth={1.5} />
              </div>
              <div className="stat-elegant-content">
                <div className="stat-elegant-value">{totalLessons}</div>
                <div className="stat-elegant-label">Занятий</div>
              </div>
            </div>
            <div className="stat-elegant-item">
              <div className="stat-elegant-icon">
                <Star size={22} strokeWidth={1.5} />
              </div>
              <div className="stat-elegant-content">
                <div className="stat-elegant-value">{averageRating}</div>
                <div className="stat-elegant-label">Рейтинг</div>
              </div>
            </div>
            <div className="stat-elegant-item">
              <div className="stat-elegant-icon">
                <Calendar size={22} strokeWidth={1.5} />
              </div>
              <div className="stat-elegant-content">
                <div className="stat-elegant-value">{upcomingLessons}</div>
                <div className="stat-elegant-label">Предстоящих</div>
              </div>
            </div>
            <div className="stat-elegant-item">
              <div className="stat-elegant-icon">
                <Award size={22} strokeWidth={1.5} />
              </div>
              <div className="stat-elegant-content">
                <div className="stat-elegant-value">{completedLessons}</div>
                <div className="stat-elegant-label">Завершено</div>
              </div>
            </div>
          </div>
        </motion.section>

        <ImageSlider />

        <motion.section 
          className="lessons-elegant"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.6, delay: 0.4 }}
        >
          <div className="section-header-elegant">
            <h2 className="section-title-elegant">Мои занятия</h2>
            <div className="section-divider"></div>
          </div>
          {lessons.length === 0 ? (
            <div className="empty-elegant">
              <div className="empty-icon-elegant">
                <PenTool size={48} strokeWidth={1.5} />
              </div>
              <h3 className="empty-title-elegant">Начните свой творческий путь</h3>
              <p className="empty-text-elegant">
                Запишитесь на первое занятие и откройте для себя мир искусства
              </p>
            </div>
          ) : (
            <div className="lessons-timeline">
              {lessons.map((lesson, index) => {
                const date = new Date(lesson.date)
                const formattedDate = date.toLocaleDateString('ru-RU', { 
                  day: 'numeric', 
                  month: 'long',
                  year: 'numeric'
                })
                
                return (
                  <motion.div
                    key={lesson.id}
                    className="lesson-timeline-item"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: index * 0.05, duration: 0.3 }}
                  >
                    <div className="timeline-marker">
                      <div className="marker-dot"></div>
                      <div className="marker-line"></div>
                    </div>
                    <div className="lesson-timeline-content">
                      <div className="lesson-timeline-header">
                        <div className="lesson-technique-elegant">{lesson.technique}</div>
                        <div className="lesson-rating-elegant">
                          {Array.from({ length: 5 }).map((_, i) => (
                            <Star
                              key={i}
                              size={14}
                              fill={i < lesson.rating ? '#2C3E50' : 'transparent'}
                              stroke={i < lesson.rating ? '#2C3E50' : '#BDC3C7'}
                              strokeWidth={1.5}
                            />
                          ))}
                        </div>
                      </div>
                      <h3 className="lesson-work-title-elegant">{lesson.workTitle}</h3>
                      <div className="lesson-details-elegant">
                        <div className="lesson-detail-elegant">
                          <User size={14} strokeWidth={1.5} />
                          <span>{lesson.instructor}</span>
                        </div>
                        <div className="lesson-detail-elegant">
                          <Calendar size={14} strokeWidth={1.5} />
                          <span>{formattedDate}</span>
                        </div>
                      </div>
                      <div className="lesson-rating-bar">
                        <div className="rating-bar-fill" style={{ width: `${(lesson.rating / 5) * 100}%` }}></div>
                        <span className="rating-text">Оценка: {lesson.rating}/5</span>
                      </div>
                    </div>
                  </motion.div>
                )
              })}
            </div>
          )}
        </motion.section>

        <motion.section 
          className="techniques-elegant"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.6, delay: 0.6 }}
        >
          <div className="section-header-elegant">
            <h2 className="section-title-elegant">Техники рисования</h2>
            <div className="section-divider"></div>
          </div>
          <div className="techniques-grid">
            {[
              { name: 'Акварель', description: 'Легкость и прозрачность красок' },
              { name: 'Графика', description: 'Точность линий и штриховка' },
              { name: 'Масло', description: 'Богатство цвета и фактуры' },
              { name: 'Цифровое', description: 'Современные технологии в искусстве' }
            ].map((technique, index) => (
              <motion.div
                key={index}
                className="technique-item-elegant"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: index * 0.05 }}
                whileHover={{ y: -3 }}
              >
                <div className="technique-icon-elegant">
                  <PenTool size={28} strokeWidth={1.5} />
                </div>
                <h3 className="technique-name-elegant">{technique.name}</h3>
                <p className="technique-description-elegant">{technique.description}</p>
              </motion.div>
            ))}
          </div>
        </motion.section>
      </div>
    </div>
  )
}

export default MyLessons

