import { useState, useEffect } from 'react'
import { ChefHat, History, Calendar, Star, Apple, BookOpen } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './MyParticipations.css'

const sliderImages = [
  '/images/cooking-1.jpg',
  '/images/cooking-2.jpg',
  '/images/cooking-3.jpg',
  '/images/cooking-4.jpg'
]

function MyParticipations() {
  const [participations, setParticipations] = useState([])

  useEffect(() => {
    const saved = localStorage.getItem('cookingParticipations')
    if (saved) {
      try {
        const parsed = JSON.parse(saved)
        setParticipations(parsed.past || parsed || [])
      } catch (e) {
        console.error('Error parsing participations:', e)
        setParticipations([])
      }
    } else {
      const defaultParticipations = {
        past: [
          {
            id: 1,
            title: 'Искусство выпечки хлеба',
            date: '2025-03-15',
            rating: 5
          },
          {
            id: 2,
            title: 'Десерты без сахара',
            date: '2025-03-10',
            rating: 4
          },
          {
            id: 3,
            title: 'Секреты азиатской кухни',
            date: '2025-03-05',
            rating: 5
          }
        ]
      }
      localStorage.setItem('cookingParticipations', JSON.stringify(defaultParticipations))
      setParticipations(defaultParticipations.past)
    }
  }, [])

  const handleRating = (id, rating) => {
    const updated = participations.map(p => 
      p.id === id ? { ...p, rating } : p
    )
    setParticipations(updated)
    localStorage.setItem('cookingParticipations', JSON.stringify({ past: updated }))
  }

  return (
    <div className="my-participations">
      <div className="container">
        <section className="page-intro">
          <div className="intro-content">
            <div className="intro-icon-wrapper">
              <ChefHat className="intro-main-icon" size={64} />
            </div>
            <h1 className="intro-title">Мои участия</h1>
            <p className="intro-description">
              История ваших кулинарных мастер-классов. Отслеживайте пройденные занятия и оценивайте их.
            </p>
            <div className="intro-stats">
              {[
                { value: participations.length, label: 'Пройдено', color: '#FF6B35' },
                { value: participations.filter(p => p.rating === 5).length, label: 'Отлично', color: '#F7931E' },
                { value: participations.reduce((sum, p) => sum + (p.rating || 0), 0) / participations.length || 0, label: 'Средний рейтинг', color: '#FFB84D' }
              ].map((stat, index) => (
                <div key={index} className="intro-stat">
                  <div className="intro-stat-value" style={{ color: stat.color }}>
                    {typeof stat.value === 'number' && stat.value % 1 !== 0 ? stat.value.toFixed(1) : stat.value}
                  </div>
                  <div className="intro-stat-label">{stat.label}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="intro-decorations">
            <div className="decoration decoration-1"></div>
            <div className="decoration decoration-2"></div>
            <div className="decoration decoration-3"></div>
          </div>
        </section>

        <ImageSlider images={sliderImages} />

        <section className="participations-section">
          <div className="section-header">
            <h2 className="section-title">
              <History className="section-icon" size={24} />
              История участий
            </h2>
          </div>
          <div className="participations-container">
            {participations.length === 0 ? (
              <div className="empty-state">
                <ChefHat className="empty-icon" size={64} />
                <p>Вы еще не участвовали в мастер-классах</p>
              </div>
            ) : (
              participations.map(participation => (
                <div key={participation.id} className="participation-card">
                  <div className="participation-header">
                    <div className="participation-title-wrapper">
                      <ChefHat className="participation-icon" size={32} />
                      <h3 className="participation-title">{participation.title}</h3>
                    </div>
                  </div>
                  <div className="participation-date">
                    <Calendar className="detail-icon" size={18} />
                    <span>{new Date(participation.date).toLocaleDateString('ru-RU', { 
                      day: 'numeric', 
                      month: 'long', 
                      year: 'numeric' 
                    })}</span>
                  </div>
                  {!participation.rating ? (
                    <div className="rating-section">
                      <div className="rating-label">Оцените мастер-класс:</div>
                      <div className="stars-container">
                        {[1, 2, 3, 4, 5].map(star => (
                          <button
                            key={star}
                            className="star-btn"
                            onClick={() => handleRating(participation.id, star)}
                          >
                            <Star className="star-icon" size={24} />
                          </button>
                        ))}
                      </div>
                    </div>
                  ) : (
                    <div className="rating-display">
                      <div className="rating-label">Ваша оценка:</div>
                      <div className="stars-container">
                        {[1, 2, 3, 4, 5].map(star => (
                          <Star
                            key={star}
                            className={`star-icon ${star <= participation.rating ? 'filled' : ''}`}
                            size={24}
                          />
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              ))
            )}
          </div>
        </section>

        <section className="info-section">
          <h2 className="info-title">Почему выбирают нас?</h2>
          <div className="info-grid">
            <div className="info-card">
              <ChefHat className="info-icon" size={40} />
              <h3>Опытные шеф-повара</h3>
              <p>Профессионалы с многолетним опытом</p>
            </div>
            <div className="info-card">
              <Apple className="info-icon" size={40} />
              <h3>Свежие продукты</h3>
              <p>Только качественные ингредиенты</p>
            </div>
            <div className="info-card">
              <BookOpen className="info-icon" size={40} />
              <h3>Уникальные рецепты</h3>
              <p>Эксклюзивные блюда и техники</p>
            </div>
          </div>
        </section>
      </div>
    </div>
  )
}

export default MyParticipations

