import { useState, useEffect } from 'react'
import { Star, Users, Award, TrendingUp, Heart, Calendar, Clock, User } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './MyBookings.css'

const MyBookings = () => {
  const [activeTab, setActiveTab] = useState('active')
  const [bookings, setBookings] = useState({
    active: [],
    past: []
  })

  useEffect(() => {
    const savedBookings = localStorage.getItem('fitnessBookings')
    if (savedBookings) {
      const parsed = JSON.parse(savedBookings)
      setBookings(parsed)
    } else {
      const defaultBookings = {
        active: [
          {
            id: 1,
            type: 'Йога',
            date: '2025-03-20',
            time: '18:00',
            trainer: 'Анна Петрова',
            status: 'active'
          },
          {
            id: 2,
            type: 'Кроссфит',
            date: '2025-03-22',
            time: '19:30',
            trainer: 'Иван Сидоров',
            status: 'active'
          },
          {
            id: 3,
            type: 'Пилатес',
            date: '2025-03-24',
            time: '17:00',
            trainer: 'Мария Козлова',
            status: 'active'
          }
        ],
        past: [
          {
            id: 4,
            type: 'Йога',
            date: '2025-03-15',
            time: '18:00',
            trainer: 'Анна Петрова',
            rating: 5
          },
          {
            id: 5,
            type: 'Стретчинг',
            date: '2025-03-10',
            time: '20:00',
            trainer: 'Ольга Новикова',
            rating: 4
          },
          {
            id: 6,
            type: 'Кроссфит',
            date: '2025-03-08',
            time: '19:30',
            trainer: 'Иван Сидоров',
            rating: 5
          }
        ]
      }
      setBookings(defaultBookings)
      localStorage.setItem('fitnessBookings', JSON.stringify(defaultBookings))
    }

    const handleStorageChange = () => {
      const updated = localStorage.getItem('fitnessBookings')
      if (updated) {
        setBookings(JSON.parse(updated))
      }
    }

    window.addEventListener('storage', handleStorageChange)
    const interval = setInterval(handleStorageChange, 500)

    return () => {
      window.removeEventListener('storage', handleStorageChange)
      clearInterval(interval)
    }
  }, [])

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

  const handleRating = (bookingId, rating) => {
    const updatedBookings = {
      ...bookings,
      past: bookings.past.map(booking => 
        booking.id === bookingId ? { ...booking, rating } : booking
      )
    }
    setBookings(updatedBookings)
    localStorage.setItem('fitnessBookings', JSON.stringify(updatedBookings))
  }

  const stats = [
    { icon: Users, value: '150+', label: 'Активных клиентов' },
    { icon: Award, value: '25+', label: 'Профессиональных тренеров' },
    { icon: TrendingUp, value: '98%', label: 'Довольных клиентов' },
    { icon: Heart, value: '500+', label: 'Тренировок в месяц' }
  ]

  return (
    <div className="bookings-page">
      <div className="hero-section">
        <div className="header-shapes">
          <div className="shape shape-1"></div>
          <div className="shape shape-2"></div>
          <div className="shape shape-3"></div>
          <div className="shape shape-4"></div>
        </div>
        <h1 className="page-title">Добро пожаловать в FitFlow</h1>
        <p className="page-subtitle">Ваш путь к здоровому образу жизни начинается здесь</p>
      </div>

      <div className="stats-section">
        {stats.map((stat, index) => {
          const IconComponent = stat.icon
          return (
            <div key={index} className="stat-card">
              <IconComponent className="stat-icon" size={40} />
              <div className="stat-value">{stat.value}</div>
              <div className="stat-label">{stat.label}</div>
            </div>
          )
        })}
      </div>

      <ImageSlider images={sliderImages} />
      
      <div className="tabs">
        <button
          className={`tab ${activeTab === 'active' ? 'active' : ''}`}
          onClick={() => setActiveTab('active')}
        >
          Активные
        </button>
        <button
          className={`tab ${activeTab === 'past' ? 'active' : ''}`}
          onClick={() => setActiveTab('past')}
        >
          Прошедшие
        </button>
      </div>

      <div className="bookings-list">
        {activeTab === 'active' ? (
          bookings.active.length > 0 ? (
            bookings.active.map((booking) => (
              <div key={booking.id} className="booking-card active">
                <div className="booking-header">
                  <h3 className="booking-type">{booking.type}</h3>
                  <span className="status-badge active">Активна</span>
                </div>
                <div className="booking-details">
                  <div className="detail-item">
                    <Calendar className="detail-icon" size={20} />
                    <span>{new Date(booking.date).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })}</span>
                  </div>
                  <div className="detail-item">
                    <Clock className="detail-icon" size={20} />
                    <span>{booking.time}</span>
                  </div>
                  <div className="detail-item">
                    <User className="detail-icon" size={20} />
                    <span>{booking.trainer}</span>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="empty-state">Нет активных записей</div>
          )
        ) : (
          bookings.past.length > 0 ? (
            bookings.past.map((booking) => (
              <div key={booking.id} className="booking-card past">
                <div className="booking-header">
                  <h3 className="booking-type">{booking.type}</h3>
                  <span className="status-badge past">Завершена</span>
                </div>
                <div className="booking-details">
                  <div className="detail-item">
                    <Calendar className="detail-icon" size={20} />
                    <span>{new Date(booking.date).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })}</span>
                  </div>
                  <div className="detail-item">
                    <Clock className="detail-icon" size={20} />
                    <span>{booking.time}</span>
                  </div>
                  <div className="detail-item">
                    <User className="detail-icon" size={20} />
                    <span>{booking.trainer}</span>
                  </div>
                </div>
                <div className="rating-section">
                  <p className="rating-label">Оцените тренера:</p>
                  <div className="rating-stars">
                    {[1, 2, 3, 4, 5].map((star) => (
                      <button
                        key={star}
                        className={`star-btn ${booking.rating >= star ? 'filled' : ''}`}
                        onClick={() => handleRating(booking.id, star)}
                      >
                        <Star size={24} fill={booking.rating >= star ? 'currentColor' : 'none'} />
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="empty-state">Нет прошедших записей</div>
          )
        )}
      </div>
    </div>
  )
}

export default MyBookings

