import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { BookOpen, User, Award, Star, Package, CheckCircle, Rocket, TrendingUp, Sparkles, Heart, 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-creative">
      <div className="container">
        <section className="page-header-creative">
          <div className="header-badge-creative">
            <Rocket size={20} />
            <span>ВАШИ КУРСЫ</span>
          </div>
          <h1 className="page-title-creative">
            Мои <span className="title-accent-creative">курсы</span>
          </h1>
          <p className="page-description-creative">
            Отслеживайте прогресс обучения, общайтесь с наставниками и получайте сертификаты
          </p>
        </section>

        <ImageSlider />

        <SuccessStoriesSection />

        <InspirationSection />

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

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

const SuccessStoriesSection = () => {
  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 stories = [
    {
      icon: TrendingUp,
      title: 'Рост дохода на 300%',
      description: 'Выпускник курса по контекстной рекламе увеличил доход клиента в 3 раза за 3 месяца',
      gradient: 'linear-gradient(135deg, #FF006E 0%, #FF6B35 100%)'
    },
    {
      icon: Sparkles,
      title: 'Вирусный контент',
      description: 'Студентка курса SMM создала пост, который набрал 2 млн просмотров за неделю',
      gradient: 'linear-gradient(135deg, #8338EC 0%, #FF006E 100%)'
    },
    {
      icon: Heart,
      title: 'Карьерный рост',
      description: 'Выпускник получил повышение до директора по маркетингу после прохождения курса',
      gradient: 'linear-gradient(135deg, #FF6B35 0%, #FFBE0B 100%)'
    }
  ]

  return (
    <section 
      ref={sectionRef}
      className={`success-stories-section-creative ${isVisible ? 'visible' : ''}`}
    >
      <div className="container">
        <div className="success-stories-header-creative">
          <h2 className="success-stories-title-creative">Истории успеха</h2>
          <p className="success-stories-description-creative">
            Реальные результаты наших выпускников
          </p>
        </div>
        <div className="success-stories-grid-creative">
          {stories.map((story, index) => {
            const Icon = story.icon
            return (
              <div 
                key={index} 
                className="story-card-creative"
                style={{ 
                  animationDelay: `${index * 0.15}s`,
                  background: story.gradient
                }}
              >
                <div className="story-icon-wrapper-creative">
                  <Icon size={40} />
                </div>
                <h3 className="story-title-creative">{story.title}</h3>
                <p className="story-text-creative">{story.description}</p>
              </div>
            )
          })}
        </div>
      </div>
    </section>
  )
}

const InspirationSection = () => {
  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 inspirations = [
    {
      quote: 'Маркетинг — это не наука, это искусство убеждения.',
      author: 'Филип Котлер',
      color: 'var(--creative-pink)'
    },
    {
      quote: 'Лучший маркетинг — это когда клиент становится вашим промоутером.',
      author: 'Сет Годин',
      color: 'var(--creative-orange)'
    },
    {
      quote: 'Не продавайте продукт, продавайте решение проблемы.',
      author: 'Дэвид Огилви',
      color: 'var(--creative-purple)'
    }
  ]

  return (
    <section 
      ref={sectionRef}
      className={`inspiration-section-creative ${isVisible ? 'visible' : ''}`}
    >
      <div className="container">
        <div className="inspiration-header-creative">
          <h2 className="inspiration-title-creative">Вдохновляющие цитаты</h2>
          <p className="inspiration-description-creative">
            Мудрость великих маркетологов
          </p>
        </div>
        <div className="inspiration-grid-creative">
          {inspirations.map((item, index) => (
            <div 
              key={index} 
              className="inspiration-card-creative"
              style={{ 
                animationDelay: `${index * 0.15}s`,
                '--inspiration-color': item.color
              }}
            >
              <div className="inspiration-quote-mark">"</div>
              <p className="inspiration-quote-creative">{item.quote}</p>
              <div className="inspiration-author-creative">— {item.author}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  )
}

export default MyCourses

