import { useState, useEffect } from 'react'
import { Package, Calendar, History, Star, Volume2, Lightbulb, Sofa, CheckCircle, Circle, Package as PackageIcon } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './MyRentals.css'

const MyRentals = () => {
  const [rentals, setRentals] = useState({
    active: [],
    past: []
  })

  useEffect(() => {
    const savedRentals = localStorage.getItem('equipmentRentals')
    if (savedRentals) {
      const parsed = JSON.parse(savedRentals)
      setRentals(parsed)
    } else {
      const defaultRentals = {
        active: [
          {
            id: 1,
            category: 'Звуковое оборудование',
            items: ['Микрофоны', 'Колонки', 'Микшерный пульт'],
            startDate: '2025-12-25',
            endDate: '2025-12-28',
            status: 'Активна',
            total: 15000
          },
          {
            id: 2,
            category: 'Освещение',
            items: ['Прожекторы', 'Светодиодные панели'],
            startDate: '2025-12-26',
            endDate: '2025-12-29',
            status: 'Активна',
            total: 12000
          },
          {
            id: 3,
            category: 'Мебель',
            items: ['Столы', 'Стулья', 'Диваны'],
            startDate: '2025-12-27',
            endDate: '2025-12-30',
            status: 'Активна',
            total: 8000
          }
        ],
        past: [
          {
            id: 4,
            category: 'Звуковое оборудование',
            items: ['Микрофоны', 'Колонки'],
            startDate: '2025-12-15',
            endDate: '2025-12-18',
            status: 'Завершена',
            total: 10000,
            rating: 5,
            review: 'Отличное оборудование, все работало идеально!'
          },
          {
            id: 5,
            category: 'Освещение',
            items: ['Прожекторы', 'Светодиодные панели'],
            startDate: '2025-12-10',
            endDate: '2025-12-12',
            status: 'Завершена',
            total: 12000,
            rating: 4
          },
          {
            id: 6,
            category: 'Мебель',
            items: ['Столы', 'Стулья'],
            startDate: '2025-12-05',
            endDate: '2025-12-08',
            status: 'Завершена',
            total: 8000,
            rating: 5
          }
        ]
      }
      setRentals(defaultRentals)
      localStorage.setItem('equipmentRentals', JSON.stringify(defaultRentals))
    }

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

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

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

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

  const handleRating = (rentalId, rating) => {
    const updatedRentals = {
      ...rentals,
      past: rentals.past.map(rental => 
        rental.id === rentalId ? { ...rental, rating } : rental
      )
    }
    setRentals(updatedRentals)
    localStorage.setItem('equipmentRentals', JSON.stringify(updatedRentals))
  }

  const handleReview = (rentalId, review) => {
    const updatedRentals = {
      ...rentals,
      past: rentals.past.map(rental => 
        rental.id === rentalId ? { ...rental, review } : rental
      )
    }
    setRentals(updatedRentals)
    localStorage.setItem('equipmentRentals', JSON.stringify(updatedRentals))
  }

  const getCategoryIcon = (category) => {
    if (category.includes('Звук')) return Volume2
    if (category.includes('Освещение')) return Lightbulb
    if (category.includes('Мебель')) return Sofa
    return PackageIcon
  }

  const getStatusColor = (status) => {
    if (status === 'Активна') return '#10b981'
    if (status === 'Завершена') return '#64748b'
    return '#f59e0b'
  }

  const stats = [
    { icon: CheckCircle, value: rentals.active.length, label: 'Активных', color: '#10b981' },
    { icon: Circle, value: rentals.past.length, label: 'Завершено', color: '#64748b' },
    { icon: Package, value: rentals.active.length + rentals.past.length, label: 'Всего', color: '#4f46e5' }
  ]

  return (
    <div className="my-rentals">
      <div className="container">
        <section className="welcome-banner">
          <div className="banner-content">
            <div className="banner-icon-wrapper">
              <Package className="banner-main-icon" size={64} />
            </div>
            <h1 className="banner-title">Мои аренды</h1>
            <p className="banner-description">Управляйте своими арендованными оборудованием и отслеживайте статус заказов</p>
            <div className="banner-stats-inline">
              {stats.map((stat, index) => (
                <div key={index} className="banner-stat">
                  <div className="banner-stat-value" style={{ 
                    background: `linear-gradient(135deg, ${stat.color}, ${stat.color}dd)`,
                    WebkitBackgroundClip: 'text',
                    WebkitTextFillColor: 'transparent',
                    backgroundClip: 'text',
                    filter: `drop-shadow(0 0 10px ${stat.color}80)`
                  }}>
                    {stat.value}
                  </div>
                  <div className="banner-stat-label">{stat.label}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="banner-decorations">
            <div className="decoration decoration-1"></div>
            <div className="decoration decoration-2"></div>
            <div className="decoration decoration-3"></div>
            <div className="decoration decoration-4"></div>
            <div className="decoration decoration-5"></div>
          </div>
        </section>

        <ImageSlider images={sliderImages} />

        <section className="rentals-section">
          <div className="section-header">
            <h2 className="section-title">
              <Package className="section-icon" size={24} />
              Активные аренды
            </h2>
          </div>
          <div className="rentals-container">
            {rentals.active.length === 0 ? (
              <div className="empty-state">
                <Package className="empty-icon" size={64} />
                <p>Нет активных аренд</p>
              </div>
            ) : (
              rentals.active.map(rental => (
                <div key={rental.id} className="rental-card">
                  <div className="rental-header">
                    <div className="rental-category">
                      {(() => {
                        const IconComponent = getCategoryIcon(rental.category)
                        return <IconComponent className="category-icon" size={28} />
                      })()}
                      <span className="category-name">{rental.category}</span>
                    </div>
                    <span className="rental-status" style={{ backgroundColor: getStatusColor(rental.status) + '20', color: getStatusColor(rental.status) }}>
                      {rental.status}
                    </span>
                  </div>
                  <div className="rental-items">
                    {rental.items.map((item, idx) => (
                      <span key={idx} className="rental-item-tag">{item}</span>
                    ))}
                  </div>
                  <div className="rental-bottom-section">
                    <div className="rental-dates">
                      <div className="rental-date">
                        <Calendar className="detail-icon" size={18} />
                        <span>С {new Date(rental.startDate).toLocaleDateString('ru-RU')}</span>
                      </div>
                      <div className="rental-date">
                        <Calendar className="detail-icon" size={18} />
                        <span>По {new Date(rental.endDate).toLocaleDateString('ru-RU')}</span>
                      </div>
                    </div>
                    <div className="rental-total">
                      <span className="total-label">Сумма:</span>
                      <span className="total-value">{rental.total.toLocaleString('ru-RU')} ₽</span>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </section>

        <section className="rentals-section">
          <div className="section-header">
            <h2 className="section-title">
              <History className="section-icon" size={24} />
              История аренд
            </h2>
          </div>
          <div className="rentals-container">
            {rentals.past.length === 0 ? (
              <div className="empty-state">
                <Package className="empty-icon" size={64} />
                <p>Нет завершенных аренд</p>
              </div>
            ) : (
              rentals.past.map(rental => (
                <div key={rental.id} className="rental-card past">
                  <div className="rental-header">
                    <div className="rental-category">
                      {(() => {
                        const IconComponent = getCategoryIcon(rental.category)
                        return <IconComponent className="category-icon" size={28} />
                      })()}
                      <span className="category-name">{rental.category}</span>
                    </div>
                    <span className="rental-status" style={{ backgroundColor: getStatusColor(rental.status) + '20', color: getStatusColor(rental.status) }}>
                      {rental.status}
                    </span>
                  </div>
                  <div className="rental-items">
                    {rental.items.map((item, idx) => (
                      <span key={idx} className="rental-item-tag">{item}</span>
                    ))}
                  </div>
                  <div className="rental-bottom-section">
                    <div className="rental-dates">
                      <div className="rental-date">
                        <Calendar className="detail-icon" size={18} />
                        <span>С {new Date(rental.startDate).toLocaleDateString('ru-RU')}</span>
                      </div>
                      <div className="rental-date">
                        <Calendar className="detail-icon" size={18} />
                        <span>По {new Date(rental.endDate).toLocaleDateString('ru-RU')}</span>
                      </div>
                    </div>
                    <div className="rental-total">
                      <span className="total-label">Сумма:</span>
                      <span className="total-value">{rental.total.toLocaleString('ru-RU')} ₽</span>
                    </div>
                  </div>
                  {!rental.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(rental.id, star)}
                          >
                            <Star className="star-icon" size={24} />
                          </button>
                        ))}
                      </div>
                    </div>
                  )}
                  {rental.rating && (
                    <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 <= rental.rating ? 'filled' : ''}`}
                            size={24}
                          />
                        ))}
                      </div>
                    </div>
                  )}
                  {rental.rating && !rental.review && (
                    <div className="review-section">
                      <textarea
                        className="review-input"
                        placeholder="Оставьте отзыв о вашей аренде..."
                        rows="3"
                        onBlur={(e) => handleReview(rental.id, e.target.value)}
                      />
                    </div>
                  )}
                  {rental.review && (
                    <div className="review-display">
                      <div className="review-label">Ваш отзыв:</div>
                      <p className="review-text">{rental.review}</p>
                    </div>
                  )}
                </div>
              ))
            )}
          </div>
        </section>
      </div>
    </div>
  )
}

export default MyRentals

