import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Brush, User, Calendar, Star, Palette, 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-creative"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
        >
          <div className="hero-content-creative">
            <motion.div 
              className="hero-badge-creative"
              initial={{ scale: 0, rotate: -180 }}
              animate={{ scale: 1, rotate: 0 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
            >
              <Palette size={20} strokeWidth={2.5} />
              <span>ТВОРЧЕСТВО БЕЗ ГРАНИЦ</span>
            </motion.div>
            <h1 className="hero-title-creative">
              Мои <span className="title-gradient">занятия</span>
            </h1>
            <p className="hero-description-creative">
              Отслеживайте свой творческий путь. Каждое занятие — это шаг к мастерству, 
              каждая работа — отражение вашего роста как художника.
            </p>
          </div>
        </motion.section>

        <motion.section 
          className="stats-creative"
          initial={{ opacity: 0, y: 40 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, delay: 0.3 }}
        >
          <div className="stats-palette">
            <motion.div 
              className="stat-palette-item"
              whileHover={{ y: -3 }}
              transition={{ duration: 0.2 }}
            >
              <div className="stat-palette-icon" style={{ background: 'var(--gradient-1)' }}>
                <Brush size={28} strokeWidth={2.5} />
              </div>
              <div className="stat-palette-content">
                <div className="stat-palette-value">{totalLessons}</div>
                <div className="stat-palette-label">Всего занятий</div>
              </div>
            </motion.div>
            <motion.div 
              className="stat-palette-item"
              whileHover={{ y: -3 }}
              transition={{ duration: 0.2 }}
            >
              <div className="stat-palette-icon" style={{ background: 'var(--gradient-2)' }}>
                <Star size={28} strokeWidth={2.5} />
              </div>
              <div className="stat-palette-content">
                <div className="stat-palette-value">{averageRating}</div>
                <div className="stat-palette-label">Средняя оценка</div>
              </div>
            </motion.div>
            <motion.div 
              className="stat-palette-item"
              whileHover={{ y: -3 }}
              transition={{ duration: 0.2 }}
            >
              <div className="stat-palette-icon" style={{ background: 'var(--gradient-3)' }}>
                <Calendar size={28} strokeWidth={2.5} />
              </div>
              <div className="stat-palette-content">
                <div className="stat-palette-value">{upcomingLessons}</div>
                <div className="stat-palette-label">Предстоящих</div>
              </div>
            </motion.div>
            <motion.div 
              className="stat-palette-item"
              whileHover={{ y: -3 }}
              transition={{ duration: 0.2 }}
            >
              <div className="stat-palette-icon" style={{ background: 'var(--gradient-4)' }}>
                <Award size={28} strokeWidth={2.5} />
              </div>
              <div className="stat-palette-content">
                <div className="stat-palette-value">{completedLessons}</div>
                <div className="stat-palette-label">Завершено</div>
              </div>
            </motion.div>
          </div>
        </motion.section>

        <ImageSlider />

        <motion.section 
          className="lessons-creative"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.8, delay: 0.5 }}
        >
          <div className="section-header-creative">
            <div className="section-brush"></div>
            <h2 className="section-title-creative">Мои занятия</h2>
            <div className="section-brush"></div>
          </div>
          {lessons.length === 0 ? (
            <div className="empty-creative">
              <div className="empty-palette">
                <Palette size={64} strokeWidth={2} />
              </div>
              <h3 className="empty-title-creative">Начните свой творческий путь</h3>
              <p className="empty-text-creative">
                Запишитесь на первое занятие и откройте для себя мир искусства
              </p>
            </div>
          ) : (
            <div className="lessons-canvas">
              {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-card-creative"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: index * 0.05, duration: 0.3 }}
                    whileHover={{ y: -4 }}
                  >
                    <div className="lesson-card-main">
                      <div className="lesson-card-header">
                        <div className="lesson-technique-badge" style={{ background: 'var(--gradient-1)' }}>
                          {lesson.technique}
                        </div>
                        <div className="lesson-rating">
                          {Array.from({ length: 5 }).map((_, i) => (
                            <Star
                              key={i}
                              size={16}
                              fill={i < lesson.rating ? '#FFD93D' : 'transparent'}
                              stroke={i < lesson.rating ? '#FFD93D' : '#E0E0E0'}
                              strokeWidth={2}
                            />
                          ))}
                        </div>
                      </div>
                      <h3 className="lesson-work-title">{lesson.workTitle}</h3>
                      <div className="lesson-info-grid">
                        <div className="lesson-info-item">
                          <User size={16} strokeWidth={2} />
                          <span>{lesson.instructor}</span>
                        </div>
                        <div className="lesson-info-item">
                          <Calendar size={16} strokeWidth={2} />
                          <span>{formattedDate}</span>
                        </div>
                      </div>
                    </div>
                    <div className="lesson-card-footer">
                      <div className="lesson-progress-bar">
                        <motion.div 
                          className="lesson-progress-fill"
                          initial={{ width: 0 }}
                          animate={{ width: `${(lesson.rating / 5) * 100}%` }}
                          transition={{ delay: index * 0.05 + 0.2, duration: 0.6 }}
                          style={{ background: 'var(--gradient-1)' }}
                        />
                      </div>
                      <span className="lesson-progress-text">{lesson.rating}/5</span>
                    </div>
                  </motion.div>
                )
              })}
            </div>
          )}
        </motion.section>

      </div>
    </div>
  )
}

export default MyLessons

