import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Calendar, Building2, Stethoscope, Star, Heart, AlertCircle, TrendingUp } from 'lucide-react'
import ImageSlider from '../components/ImageSlider'
import './VisitHistory.css'

const VisitHistory = () => {
  const [visits, setVisits] = useState({ active: [], past: [] })
  const [activeTab, setActiveTab] = useState('active')

  useEffect(() => {
    loadVisits()
    const interval = setInterval(loadVisits, 500)
    return () => clearInterval(interval)
  }, [])

  const loadVisits = () => {
    const saved = localStorage.getItem('dentalVisits')
    if (saved) {
      try {
        setVisits(JSON.parse(saved))
      } catch (e) {
        setVisits({ active: [], past: [] })
      }
    } else {
      const defaultVisits = {
        active: [
          {
            id: 1,
            clinic: 'Стоматология "Улыбка"',
            service: 'Осмотр',
            date: '2025-03-28',
            status: 'active'
          },
          {
            id: 2,
            clinic: 'Клиника "ДентПро"',
            service: 'Пломба',
            date: '2025-03-30',
            status: 'active'
          }
        ],
        past: [
          {
            id: 3,
            clinic: 'Стоматология "Улыбка"',
            service: 'Отбеливание',
            date: '2025-03-15',
            painRating: 2,
            qualityRating: 5
          },
          {
            id: 4,
            clinic: 'Клиника "ДентПро"',
            service: 'Осмотр',
            date: '2025-03-10',
            painRating: 1,
            qualityRating: 5
          },
          {
            id: 5,
            clinic: 'Стоматология "Улыбка"',
            service: 'Пломба',
            date: '2025-03-05',
            painRating: 3,
            qualityRating: 4
          }
        ]
      }
      setVisits(defaultVisits)
      localStorage.setItem('dentalVisits', JSON.stringify(defaultVisits))
    }
  }

  const stats = [
    { 
      icon: Calendar, 
      value: visits.past.length, 
      label: 'Всего визитов',
      color: '#0EA5E9'
    },
    { 
      icon: Building2, 
      value: new Set(visits.past.map(v => v.clinic)).size, 
      label: 'Клиник посещено',
      color: '#06B6D4'
    },
    { 
      icon: Star, 
      value: visits.past.length > 0 
        ? Math.round(visits.past.reduce((sum, v) => sum + (v.qualityRating || 0), 0) / visits.past.length * 10) / 10
        : 0, 
      label: 'Средняя оценка',
      color: '#22D3EE'
    }
  ]

  const renderStars = (rating) => {
    return Array.from({ length: 5 }, (_, i) => (
      <Star
        key={i}
        size={16}
        fill={i < rating ? '#F59E0B' : 'none'}
        color={i < rating ? '#F59E0B' : '#CBD5E1'}
      />
    ))
  }

  const getPainLevel = (rating) => {
    if (rating <= 1) return { text: 'Минимальная', color: '#10B981', icon: Heart }
    if (rating <= 2) return { text: 'Легкая', color: '#22D3EE', icon: TrendingUp }
    if (rating <= 3) return { text: 'Умеренная', color: '#F59E0B', icon: AlertCircle }
    return { text: 'Сильная', color: '#EF4444', icon: AlertCircle }
  }

  return (
    <div className="visit-history">
      <section className="page-intro">
        <motion.div
          className="intro-content"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <div className="intro-icon-wrapper">
            <Stethoscope className="intro-main-icon" size={64} color="#0EA5E9" />
          </div>
          <h1 className="intro-title">История визитов</h1>
          <p className="intro-description">
            Отслеживайте свои визиты к стоматологу, оценивайте качество услуг и уровень дискомфорта
          </p>
        </motion.div>
      </section>

      <div className="container">
        <div className="stats-grid">
          {stats.map((stat, index) => (
            <motion.div
              key={stat.label}
              className="stat-card"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.1, duration: 0.5 }}
              whileHover={{ scale: 1.05, y: -5 }}
            >
              <div className="stat-icon-wrapper" style={{ background: `${stat.color}15` }}>
                <stat.icon className="stat-icon" size={32} color={stat.color} />
              </div>
              <div className="stat-content">
                <div className="stat-value">{stat.value}</div>
                <div className="stat-label">{stat.label}</div>
              </div>
            </motion.div>
          ))}
        </div>

        <ImageSlider />

        <div className="tabs">
          <button
            className={`tab ${activeTab === 'active' ? 'active' : ''}`}
            onClick={() => setActiveTab('active')}
          >
            Активные ({visits.active.length})
          </button>
          <button
            className={`tab ${activeTab === 'past' ? 'active' : ''}`}
            onClick={() => setActiveTab('past')}
          >
            История ({visits.past.length})
          </button>
        </div>

        <div className="visits-section">
          <div className="visits-grid">
            {activeTab === 'active' ? (
              visits.active.length > 0 ? (
                visits.active.map((visit) => (
                  <motion.div
                    key={visit.id}
                    className="visit-card"
                    initial={{ opacity: 0, scale: 0.9 }}
                    animate={{ opacity: 1, scale: 1 }}
                    whileHover={{ y: -8, boxShadow: '0 12px 32px rgba(14, 165, 233, 0.2)' }}
                  >
                    <div className="visit-header">
                      <Building2 className="visit-icon" size={40} color="#0EA5E9" />
                      <div className="visit-info">
                        <h3 className="visit-clinic">{visit.clinic}</h3>
                        <p className="visit-service">{visit.service}</p>
                      </div>
                    </div>
                    <div className="visit-date">
                      <Calendar className="detail-icon" size={20} color="#64748B" />
                      <span>
                        {new Date(visit.date).toLocaleDateString('ru-RU', {
                          day: 'numeric',
                          month: 'long',
                          year: 'numeric'
                        })}
                      </span>
                    </div>
                    <div className="visit-status active-badge">
                      Запланирован
                    </div>
                  </motion.div>
                ))
              ) : (
                <div className="empty-state">
                  <AlertCircle className="empty-icon" size={72} color="#CBD5E1" />
                  <p>У вас нет активных визитов</p>
                </div>
              )
            ) : (
              visits.past.length > 0 ? (
                visits.past.map((visit) => {
                  const painLevel = visit.painRating ? getPainLevel(visit.painRating) : null
                  return (
                    <motion.div
                      key={visit.id}
                      className="visit-card"
                      initial={{ opacity: 0, scale: 0.9 }}
                      animate={{ opacity: 1, scale: 1 }}
                      whileHover={{ y: -8, boxShadow: '0 12px 32px rgba(14, 165, 233, 0.2)' }}
                    >
                      <div className="visit-header">
                        <Building2 className="visit-icon" size={40} color="#0EA5E9" />
                        <div className="visit-info">
                          <h3 className="visit-clinic">{visit.clinic}</h3>
                          <p className="visit-service">{visit.service}</p>
                        </div>
                      </div>
                      <div className="visit-date">
                        <Calendar className="detail-icon" size={20} color="#64748B" />
                        <span>
                          {new Date(visit.date).toLocaleDateString('ru-RU', {
                            day: 'numeric',
                            month: 'long',
                            year: 'numeric'
                          })}
                        </span>
                      </div>
                      {visit.painRating && painLevel && (
                        <div className="visit-rating-section">
                          <div className="rating-item">
                            <span className="rating-label">Боль:</span>
                            <div className="rating-value" style={{ color: painLevel.color }}>
                              <painLevel.icon size={16} color={painLevel.color} />
                              <span>{painLevel.text}</span>
                            </div>
                          </div>
                        </div>
                      )}
                      {visit.qualityRating && (
                        <div className="visit-rating-section">
                          <div className="rating-item">
                            <span className="rating-label">Качество:</span>
                            <div className="stars-wrapper">
                              {renderStars(visit.qualityRating)}
                            </div>
                          </div>
                        </div>
                      )}
                    </motion.div>
                  )
                })
              ) : (
                <div className="empty-state">
                  <AlertCircle className="empty-icon" size={72} color="#CBD5E1" />
                  <p>История визитов пуста</p>
                </div>
              )
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default VisitHistory

