import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Shirt, Calendar, Clock, Star, Package, CheckCircle2, ArrowRight, Sparkles } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './MyRentals.css'

const MyRentals = () => {
  const [rentals, setRentals] = useState([])

  useEffect(() => {
    const saved = localStorage.getItem('costumeRentals')
    if (saved) {
      try {
        setRentals(JSON.parse(saved))
      } catch (e) {
        setRentals([])
      }
    } else {
      const defaultRentals = [
        {
          id: 1,
          costume: 'Рыцарский доспех',
          date: '2025-03-28',
          duration: '3 дня',
          review: 'Отличный костюм, все детали на месте, очень доволен!',
          rating: 5,
          category: 'Эпоха'
        },
        {
          id: 2,
          costume: 'Пиратский наряд',
          date: '2025-03-25',
          duration: '5 дней',
          review: 'Прекрасное качество, костюм выглядел очень реалистично',
          rating: 5,
          category: 'Тематика'
        },
        {
          id: 3,
          costume: 'Костюм эльфа',
          date: '2025-03-22',
          duration: '2 дня',
          review: 'Красивый костюм, отлично подошел по размеру',
          rating: 4,
          category: 'Тематика'
        }
      ]
      setRentals(defaultRentals)
      localStorage.setItem('costumeRentals', JSON.stringify(defaultRentals))
    }
  }, [])

  const totalRentals = rentals.length
  const averageRating = rentals.length > 0
    ? (rentals.reduce((sum, r) => sum + r.rating, 0) / rentals.length).toFixed(1)
    : 0
  const totalDays = rentals.reduce((sum, r) => sum + parseInt(r.duration), 0)
  const uniqueCategories = new Set(rentals.map(r => r.category)).size

  return (
    <div className="my-rentals">
      <div className="container">
        <motion.section 
          className="hero-modular"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.8 }}
        >
          <div className="hero-modular-grid">
            <motion.div 
              className="hero-modular-main"
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: 0.2 }}
            >
              <div className="hero-modular-number">{totalRentals}</div>
              <h1 className="hero-modular-title">Мои аренды</h1>
            </motion.div>
            <motion.div 
              className="hero-modular-side"
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: 0.3 }}
            >
              <div className="hero-modular-line"></div>
              <p className="hero-modular-description">
                История ваших костюмных аренд и трансформаций
              </p>
            </motion.div>
          </div>
        </motion.section>

        <motion.section 
          className="stats-geometric"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.7, delay: 0.4 }}
        >
          <div className="stats-geometric-grid">
            <motion.div 
              className="stat-geometric-square"
              whileHover={{ y: -4, transition: { duration: 0.2 } }}
            >
              <div className="stat-geometric-icon">
                <Package size={32} strokeWidth={2} color="#6366F1" />
              </div>
              <div className="stat-geometric-value">{totalRentals}</div>
              <div className="stat-geometric-label">Аренд</div>
            </motion.div>
            <motion.div 
              className="stat-geometric-circle"
              whileHover={{ y: -4, transition: { duration: 0.2 } }}
            >
              <div className="stat-geometric-icon">
                <Star size={32} strokeWidth={2} color="#6366F1" />
              </div>
              <div className="stat-geometric-value">{averageRating}</div>
              <div className="stat-geometric-label">Оценка</div>
            </motion.div>
            <motion.div 
              className="stat-geometric-diamond"
              whileHover={{ y: -4, transition: { duration: 0.2 } }}
            >
              <div className="stat-geometric-icon">
                <Calendar size={32} strokeWidth={2} color="#6366F1" />
              </div>
              <div className="stat-geometric-value">{totalDays}</div>
              <div className="stat-geometric-label">Дней</div>
            </motion.div>
            <motion.div 
              className="stat-geometric-hexagon"
              whileHover={{ y: -4, transition: { duration: 0.2 } }}
            >
              <div className="stat-geometric-icon">
                <Shirt size={32} strokeWidth={2} color="#6366F1" />
              </div>
              <div className="stat-geometric-value">{uniqueCategories}</div>
              <div className="stat-geometric-label">Категорий</div>
            </motion.div>
          </div>
        </motion.section>

        <ImageSlider images={[
          '/images/costume-1.jpg',
          '/images/costume-2.jpg',
          '/images/costume-3.jpg',
          '/images/costume-4.jpg'
        ]} />

        <motion.section 
          className="rentals-modular"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.7, delay: 0.5 }}
        >
          <div className="section-header-modular">
            <div className="section-modular-line"></div>
            <h2 className="section-modular-title">История аренд</h2>
          </div>
          {rentals.length > 0 ? (
            <div className="rentals-modular-list">
              {rentals.map((rental, index) => (
                <motion.div
                  key={rental.id}
                  className="rental-modular-item"
                  initial={{ opacity: 0, x: -30 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.6 + index * 0.1, duration: 0.5 }}
                  whileHover={{ x: 8, transition: { duration: 0.2 } }}
                >
                  <div className="rental-modular-indicator"></div>
                  <div className="rental-modular-content">
                    <div className="rental-modular-header">
                      <div className="rental-modular-category">{rental.category}</div>
                      <div className="rental-modular-rating">
                        {Array.from({ length: 5 }, (_, i) => (
                          <Star
                            key={i}
                            size={16}
                            fill={i < rental.rating ? '#6366F1' : 'none'}
                            stroke={i < rental.rating ? '#6366F1' : '#E0E0E0'}
                            strokeWidth={2}
                          />
                        ))}
                      </div>
                    </div>
                    <h3 className="rental-modular-costume">{rental.costume}</h3>
                    <div className="rental-modular-details">
                      <div className="rental-modular-detail">
                        <Calendar size={16} strokeWidth={2} color="#6366F1" />
                        <span>{new Date(rental.date).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' })}</span>
                      </div>
                      <div className="rental-modular-detail">
                        <Clock size={16} strokeWidth={2} color="#8B5CF6" />
                        <span>Срок: {rental.duration}</span>
                      </div>
                    </div>
                    {rental.review && (
                      <div className="rental-modular-review">
                        <Star size={14} strokeWidth={2} color="#A78BFA" fill="#A78BFA" />
                        <span>{rental.review}</span>
                      </div>
                    )}
                  </div>
                </motion.div>
              ))}
            </div>
          ) : (
            <div className="empty-modular">
              <div className="empty-modular-icon">
                <Shirt size={56} strokeWidth={1.5} />
              </div>
              <h3 className="empty-modular-title">Нет аренд</h3>
              <p className="empty-modular-text">Арендуйте первый костюм и увидите его здесь</p>
            </div>
          )}
        </motion.section>

        <motion.section 
          className="features-geometric"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.7, delay: 0.7 }}
        >
          <div className="features-modular-header">
            <div className="section-modular-line"></div>
            <h2 className="section-modular-title">Преимущества</h2>
          </div>
          <div className="features-geometric-grid">
            {[
              { icon: Package, title: 'Премиальное качество', text: 'Только оригинальные и качественные костюмы' },
              { icon: CheckCircle2, title: 'Огромный выбор', text: 'Более 500 костюмов различных эпох и тематик' },
              { icon: ArrowRight, title: 'Быстрая доставка', text: 'Доставка в день заказа по всему городу' },
              { icon: Star, title: 'Лучшие цены', text: 'Конкурентные цены и специальные предложения' }
            ].map((feature, index) => {
              const IconComponent = feature.icon
              return (
                <motion.div
                  key={feature.title}
                  className="feature-geometric-card"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.8 + index * 0.1, duration: 0.5 }}
                  whileHover={{ y: -4, transition: { duration: 0.2 } }}
                >
                  <div className="feature-geometric-icon">
                    <IconComponent size={32} strokeWidth={2} color="#6366F1" />
                  </div>
                  <h3 className="feature-geometric-title">{feature.title}</h3>
                  <p className="feature-geometric-text">{feature.text}</p>
                  <div className="feature-geometric-accent"></div>
                </motion.div>
              )
            })}
          </div>
        </motion.section>
      </div>
    </div>
  )
}

export default MyRentals
