import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Sparkles, Calendar, Clock, Star, Package, Award, TrendingUp, Heart, Zap, Crown, Shirt } 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 favoriteCategory = rentals.length > 0 
    ? rentals.reduce((acc, r) => {
        acc[r.category] = (acc[r.category] || 0) + 1
        return acc
      }, {})
    : {}

  return (
    <div className="my-rentals">
      <div className="container">
        <motion.section 
          className="hero-asymmetric"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.8 }}
        >
          <div className="hero-asymmetric-grid">
            <motion.div 
              className="hero-main-block"
              initial={{ x: -100, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              transition={{ duration: 0.8, delay: 0.2 }}
            >
              <motion.div 
                className="hero-number-large"
                initial={{ scale: 0, rotate: -180 }}
                animate={{ scale: 1, rotate: 0 }}
                transition={{ type: "spring", stiffness: 150, damping: 12, delay: 0.4 }}
              >
                {totalRentals}
              </motion.div>
              <h1 className="hero-title-asymmetric">Мои аренды</h1>
              <div className="hero-accent-line"></div>
            </motion.div>
            <motion.div 
              className="hero-side-block"
              initial={{ x: 100, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              transition={{ duration: 0.8, delay: 0.3 }}
            >
              <p className="hero-description-asymmetric">
                Коллекция ваших костюмных трансформаций и незабываемых образов
              </p>
              <div className="hero-stats-inline">
                <div className="hero-stat-inline">
                  <Star size={20} strokeWidth={2.5} fill="#FFB627" color="#FFB627" />
                  <span>{averageRating}</span>
                </div>
                <div className="hero-stat-inline">
                  <Calendar size={20} strokeWidth={2.5} color="#C41E3A" />
                  <span>{totalDays} дней</span>
                </div>
              </div>
            </motion.div>
          </div>
        </motion.section>

        <motion.section 
          className="stats-masonry"
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7, delay: 0.5 }}
        >
          <div className="stats-masonry-grid">
            <motion.div 
              className="stat-masonry-large"
              whileHover={{ rotate: 2, scale: 1.05, transition: { duration: 0.3 } }}
            >
              <div className="stat-masonry-icon-large">
                <Package size={56} strokeWidth={2.5} color="white" />
              </div>
              <div className="stat-masonry-content">
                <div className="stat-masonry-value-large">{totalRentals}</div>
                <div className="stat-masonry-label-large">Всего аренд</div>
              </div>
              <div className="stat-masonry-decoration"></div>
            </motion.div>
            <motion.div 
              className="stat-masonry-medium"
              whileHover={{ rotate: -1.5, scale: 1.03, transition: { duration: 0.3 } }}
            >
              <div className="stat-masonry-icon-medium">
                <Star size={44} strokeWidth={2.5} color="white" />
              </div>
              <div className="stat-masonry-content">
                <div className="stat-masonry-value-medium">{averageRating}</div>
                <div className="stat-masonry-label-medium">Средняя оценка</div>
              </div>
            </motion.div>
            <motion.div 
              className="stat-masonry-small"
              whileHover={{ rotate: 1.5, scale: 1.04, transition: { duration: 0.3 } }}
            >
              <div className="stat-masonry-icon-small">
                <Calendar size={36} strokeWidth={2.5} color="white" />
              </div>
              <div className="stat-masonry-content">
                <div className="stat-masonry-value-small">{totalDays}</div>
                <div className="stat-masonry-label-small">Дней аренды</div>
              </div>
            </motion.div>
            <motion.div 
              className="stat-masonry-wide"
              whileHover={{ rotate: -2, scale: 1.02, transition: { duration: 0.3 } }}
            >
              <div className="stat-masonry-icon-wide">
                <Heart size={40} strokeWidth={2.5} color="white" />
              </div>
              <div className="stat-masonry-content">
                <div className="stat-masonry-value-wide">{Object.keys(favoriteCategory).length}</div>
                <div className="stat-masonry-label-wide">Категорий</div>
              </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-timeline"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.7, delay: 0.6 }}
        >
          <div className="section-header-asymmetric">
            <h2 className="section-title-asymmetric">История аренд</h2>
            <div className="section-accent-dot"></div>
          </div>
          {rentals.length > 0 ? (
            <div className="rentals-timeline-container">
              {rentals.map((rental, index) => (
                <motion.div
                  key={rental.id}
                  className={`rental-timeline-item ${index % 2 === 0 ? 'left' : 'right'}`}
                  initial={{ opacity: 0, x: index % 2 === 0 ? -80 : 80 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.7 + index * 0.15, duration: 0.6, type: "spring" }}
                  whileHover={{ scale: 1.05, rotate: index % 2 === 0 ? 1 : -1, transition: { duration: 0.3 } }}
                >
                  <div className="rental-timeline-marker">
                    <div className="rental-marker-dot"></div>
                    <div className="rental-marker-line"></div>
                  </div>
                  <div className="rental-timeline-card">
                    <div className="rental-card-top">
                      <div className="rental-category-tag" style={{ 
                        background: index % 3 === 0 ? 'linear-gradient(135deg, #C41E3A 0%, #E63946 100%)' :
                        index % 3 === 1 ? 'linear-gradient(135deg, #FF6B35 0%, #FFB627 100%)' :
                        'linear-gradient(135deg, #FFB627 0%, #FFD93D 100%)'
                      }}>
                        {rental.category}
                      </div>
                      <div className="rental-rating-stars">
                        {Array.from({ length: 5 }, (_, i) => (
                          <Star
                            key={i}
                            size={16}
                            fill={i < rental.rating ? '#FFB627' : 'none'}
                            stroke={i < rental.rating ? '#FFB627' : '#E0E0E0'}
                            strokeWidth={2.5}
                          />
                        ))}
                      </div>
                    </div>
                    <h3 className="rental-costume-title">{rental.costume}</h3>
                    <div className="rental-details-grid">
                      <div className="rental-detail-box">
                        <Calendar size={18} strokeWidth={2} color="#C41E3A" />
                        <span>{new Date(rental.date).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' })}</span>
                      </div>
                      <div className="rental-detail-box">
                        <Clock size={18} strokeWidth={2} color="#FF6B35" />
                        <span>Срок: {rental.duration}</span>
                      </div>
                    </div>
                    {rental.review && (
                      <div className="rental-review-bubble">
                        <Star size={14} strokeWidth={2} color="#FFB627" fill="#FFB627" />
                        <span>{rental.review}</span>
                      </div>
                    )}
                  </div>
                </motion.div>
              ))}
            </div>
          ) : (
            <div className="empty-state-asymmetric">
              <div className="empty-icon-asymmetric">
                <Sparkles size={80} strokeWidth={1.5} />
              </div>
              <h3 className="empty-title-asymmetric">Начните свое костюмное приключение</h3>
              <p className="empty-text-asymmetric">Арендуйте первый костюм и увидите его здесь</p>
            </div>
          )}
        </motion.section>

        <motion.section 
          className="benefits-showcase"
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7, delay: 0.8 }}
        >
          <div className="benefits-header-asymmetric">
            <div className="benefits-accent-bar"></div>
            <h2 className="benefits-title-asymmetric">Почему выбирают нас</h2>
          </div>
          <div className="benefits-showcase-grid">
            {[
              { icon: Crown, title: 'Премиальное качество', text: 'Только оригинальные и качественные костюмы', accent: '#C41E3A' },
              { icon: Award, title: 'Огромный выбор', text: 'Более 500 костюмов различных эпох и тематик', accent: '#FF6B35' },
              { icon: Zap, title: 'Быстрая доставка', text: 'Доставка в день заказа по всему городу', accent: '#FFB627' },
              { icon: TrendingUp, title: 'Лучшие цены', text: 'Конкурентные цены и специальные предложения', accent: '#E63946' }
            ].map((benefit, index) => {
              const IconComponent = benefit.icon
              return (
                <motion.div
                  key={benefit.title}
                  className="benefit-showcase-card"
                  initial={{ opacity: 0, y: 40, rotate: index % 2 === 0 ? -5 : 5 }}
                  animate={{ opacity: 1, y: 0, rotate: 0 }}
                  transition={{ delay: 0.9 + index * 0.12, duration: 0.6, type: "spring" }}
                  whileHover={{ 
                    rotate: index % 2 === 0 ? 2 : -2, 
                    scale: 1.08,
                    y: -12,
                    transition: { duration: 0.3 } 
                  }}
                >
                  <div className="benefit-icon-showcase" style={{ borderColor: benefit.accent }}>
                    <IconComponent size={48} strokeWidth={2.5} color={benefit.accent} />
                    <div className="benefit-icon-bg" style={{ background: `${benefit.accent}15` }}></div>
                  </div>
                  <div className="benefit-content-showcase">
                    <h3 className="benefit-title-showcase">{benefit.title}</h3>
                    <p className="benefit-text-showcase">{benefit.text}</p>
                  </div>
                  <div className="benefit-accent-corner" style={{ background: benefit.accent }}></div>
                </motion.div>
              )
            })}
          </div>
        </motion.section>
      </div>
    </div>
  )
}

export default MyRentals
