import { Sparkles, Moon, Sun, Rocket, Orbit, Atom } from 'lucide-react'
import { memo } from 'react'

import type { CosmicVariantBlockProps } from '../types'

/**
 * Космический вариант табеля - научно-фантастическая тема
 * 
 * Особенности:
 * - Неоновые цвета и градиенты
 * - Линейное представление времени как временная шкала
 * - Научные метрики и индикаторы
 * - Анимированные элементы космической тематики
 * - Визуализация данных в стиле sci-fi интерфейсов
 */
export const CosmicVariantBlock = memo<CosmicVariantBlockProps>(function CosmicVariantBlock({
  employee,
  calendarData,
  stats,
  utils,
  selectedMonth,
  selectedYear,
}) {
  const monthName = utils.getMonthName(selectedMonth)
  const daysInMonth = utils.getDaysInMonth(selectedMonth, selectedYear)

  // Группируем дни по неделям для временной шкалы
  const weeks: number[][] = []
  let currentWeek: number[] = []
  
  for (let day = 1; day <= daysInMonth; day++) {
    currentWeek.push(day)
    if (currentWeek.length === 7 || day === daysInMonth) {
      weeks.push([...currentWeek])
      currentWeek = []
    }
  }

  const getDayData = (day: number) => {
    return calendarData.find(d => d.day === day)
  }

  const getEnergyLevel = (efficiency: number | null) => {
    if (efficiency === null) return 0
    return Math.ceil((efficiency / 100) * 4)
  }

  const getTimelineColor = (hours: number, overtime: number) => {
    const total = hours + overtime
    if (total === 0) return 'from-gray-500 to-gray-700'
    if (total <= 4) return 'from-blue-400 to-blue-600'
    if (total <= 8) return 'from-green-400 to-green-600'
    if (total <= 10) return 'from-yellow-400 to-orange-600'
    return 'from-red-400 to-red-600'
  }

  return (
    <div className="cosmic-variant">
      {/* Космическая панель управления */}
      <div className="glass-card p-8 mb-8 relative overflow-hidden">
        {/* Анимированный фон */}
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-8 left-16 w-32 h-32 border border-cyan-400 rounded-full animate-spin" style={{ animationDuration: '20s' }} />
          <div className="absolute top-16 right-24 w-16 h-16 border border-purple-400 rounded-full animate-pulse" />
          <div className="absolute bottom-8 left-1/3 w-24 h-24 border border-blue-400 rounded-full animate-spin" style={{ animationDuration: '15s', animationDirection: 'reverse' }} />
        </div>

        <div className="relative z-10">
          {/* Заголовок миссии */}
          <div className="text-center mb-8">
            <h2 className="text-3xl font-bold bg-gradient-to-r from-cyan-400 via-purple-400 to-blue-400 bg-clip-text text-transparent mb-2">
              ✨ КОСМИЧЕСКАЯ МИССИЯ: {employee.name.toUpperCase()}
            </h2>
            <p className="text-white/80 text-lg">
              {employee.position} • {employee.level} • Сектор {employee.department}
            </p>
            <p className="text-cyan-400 text-sm mt-2">
              Временной период: {monthName} {selectedYear} • Звездная дата: {Date.now()}
            </p>
          </div>

          {/* Научные индикаторы */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-6">
            <div className="text-center">
              <div className="w-20 h-20 mx-auto mb-3 relative">
                <div className="absolute inset-0 bg-gradient-to-r from-cyan-500 to-blue-500 rounded-full animate-pulse" />
                <div className="absolute inset-2 bg-gray-900 rounded-full flex items-center justify-center">
                  <Atom className="w-8 h-8 text-cyan-400" />
                </div>
              </div>
              <div className="text-2xl font-bold text-cyan-400">{stats.totalHours}</div>
              <div className="text-white/70 text-sm">Энергетических единиц</div>
            </div>

            <div className="text-center">
              <div className="w-20 h-20 mx-auto mb-3 relative">
                <div className="absolute inset-0 bg-gradient-to-r from-purple-500 to-pink-500 rounded-full animate-pulse" style={{ animationDelay: '1s' }} />
                <div className="absolute inset-2 bg-gray-900 rounded-full flex items-center justify-center">
                  <Orbit className="w-8 h-8 text-purple-400" />
                </div>
              </div>
              <div className="text-2xl font-bold text-purple-400">{stats.efficiency}%</div>
              <div className="text-white/70 text-sm">Квантовая эффективность</div>
            </div>

            <div className="text-center">
              <div className="w-20 h-20 mx-auto mb-3 relative">
                <div className="absolute inset-0 bg-gradient-to-r from-green-500 to-emerald-500 rounded-full animate-pulse" style={{ animationDelay: '2s' }} />
                <div className="absolute inset-2 bg-gray-900 rounded-full flex items-center justify-center">
                  <Rocket className="w-8 h-8 text-green-400" />
                </div>
              </div>
              <div className="text-2xl font-bold text-green-400">{stats.completedTasks}</div>
              <div className="text-white/70 text-sm">Миссий завершено</div>
            </div>

            <div className="text-center">
              <div className="w-20 h-20 mx-auto mb-3 relative">
                <div className="absolute inset-0 bg-gradient-to-r from-orange-500 to-red-500 rounded-full animate-pulse" style={{ animationDelay: '3s' }} />
                <div className="absolute inset-2 bg-gray-900 rounded-full flex items-center justify-center">
                  <Sparkles className="w-8 h-8 text-orange-400" />
                </div>
              </div>
              <div className="text-2xl font-bold text-orange-400">{stats.projects}</div>
              <div className="text-white/70 text-sm">Активных систем</div>
            </div>
          </div>
        </div>
      </div>

      {/* Временная шкала */}
      <div className="glass-card p-6 mb-8">
        <div className="flex items-center space-x-3 mb-6">
          <div className="w-8 h-8 bg-gradient-to-r from-cyan-500 to-blue-500 rounded-full flex items-center justify-center">
            <Moon className="w-4 h-4 text-white" />
          </div>
          <h3 className="text-xl font-bold text-white">Временная Континуум</h3>
          <div className="flex-1 h-px bg-gradient-to-r from-cyan-500/50 to-transparent" />
        </div>

        <div className="space-y-4">
          {weeks.map((week, weekIndex) => (
            <div key={weekIndex} className="relative">
              <div className="text-xs text-cyan-400 mb-2">Неделя {weekIndex + 1}</div>
              <div className="flex space-x-2">
                {week.map(day => {
                  const dayData = getDayData(day)
                  const totalHours = (dayData?.hours || 0) + (dayData?.overtime || 0)
                  
                  return (
                    <div key={day} className="relative group flex-1">
                      {/* Временная полоса */}
                      <div 
                        className={`
                          h-12 rounded-lg bg-gradient-to-r transition-all duration-300 cursor-pointer
                          hover:scale-y-125 hover:shadow-lg hover:shadow-cyan-500/30
                          ${dayData ? getTimelineColor(dayData.hours, dayData.overtime) : 'from-gray-700 to-gray-800'}
                        `}
                        style={{ 
                          opacity: dayData ? Math.max(0.3, totalHours / 12) : 0.2,
                        }}
                      >
                        {/* День */}
                        <div className="absolute top-1 left-2 text-xs font-bold text-white">
                          {day}
                        </div>
                        
                        {/* Часы */}
                        {dayData && totalHours > 0 && (
                          <div className="absolute bottom-1 right-2 text-xs text-white/90">
                            {totalHours}ч
                          </div>
                        )}

                        {/* Энергетический уровень */}
                        {dayData && dayData.efficiency !== null && (
                          <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
                            <div className="flex space-x-0.5">
                              {Array.from({ length: 4 }, (_, i) => (
                                <div 
                                  key={i} 
                                  className={`
                                    w-1 h-4 rounded-full transition-all duration-300
                                    ${i < getEnergyLevel(dayData.efficiency) 
                                      ? 'bg-cyan-400 shadow-lg shadow-cyan-400/50' 
                                      : 'bg-white/20'
                                    }
                                  `} 
                                />
                              ))}
                            </div>
                          </div>
                        )}
                      </div>

                      {/* Статус индикатор */}
                      {dayData && (
                        <div className="absolute -top-2 right-2">
                          {dayData.status === 'work' && <Sun className="w-3 h-3 text-yellow-400" />}
                          {dayData.status === 'remote' && <Rocket className="w-3 h-3 text-blue-400" />}
                          {dayData.status === 'vacation' && <Moon className="w-3 h-3 text-purple-400" />}
                          {dayData.status === 'sick' && <div className="w-3 h-3 bg-red-400 rounded-full" />}
                          {dayData.status === 'business' && <Orbit className="w-3 h-3 text-green-400" />}
                        </div>
                      )}

                      {/* Детальная информация при наведении */}
                      <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300 z-20 pointer-events-none">
                        <div className="bg-gray-900/95 border border-cyan-500/30 text-white text-xs rounded-lg px-3 py-2 whitespace-nowrap">
                          {dayData ? (
                            <>
                              <div className="text-cyan-400 font-bold">Звездная дата {day}</div>
                              <div>Энергия: {dayData.hours}ч</div>
                              {dayData.overtime > 0 && <div className="text-orange-400">Перегрузка: +{dayData.overtime}ч</div>}
                              <div>Эффективность: {dayData.efficiency}%</div>
                              <div>Миссий: {dayData.tasks}</div>
                              <div>Статус: {dayData.status}</div>
                            </>
                          ) : (
                            <div className="text-gray-400">Без активности</div>
                          )}
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Научные метрики */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Анализ производительности */}
        <div className="glass-card p-6">
          <h4 className="text-lg font-bold text-white mb-4 flex items-center space-x-2">
            <Atom className="w-5 h-5 text-cyan-400" />
            <span>Квантовый Анализ</span>
          </h4>
          
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <span className="text-white/70">Средняя энергия/день:</span>
              <span className="text-cyan-400 font-bold">{stats.averageHoursPerDay}ч</span>
            </div>
            
            <div className="flex justify-between items-center">
              <span className="text-white/70">Перегрузки системы:</span>
              <span className="text-orange-400 font-bold">{stats.overtime}ч</span>
            </div>
            
            <div className="flex justify-between items-center">
              <span className="text-white/70">Рабочих циклов:</span>
              <span className="text-green-400 font-bold">{stats.workDays}</span>
            </div>
            
            <div className="flex justify-between items-center">
              <span className="text-white/70">Внеплановая активность:</span>
              <span className="text-purple-400 font-bold">{stats.weekendWork} дней</span>
            </div>
          </div>
        </div>

        {/* Космическая эффективность */}
        <div className="glass-card p-6">
          <h4 className="text-lg font-bold text-white mb-4 flex items-center space-x-2">
            <Sparkles className="w-5 h-5 text-purple-400" />
            <span>Космическая Эффективность</span>
          </h4>
          
          <div className="relative">
            {/* Круговая диаграмма эффективности */}
            <div className="w-32 h-32 mx-auto mb-4 relative">
              <svg className="w-full h-full transform -rotate-90" viewBox="0 0 128 128">
                <circle
                  cx="64"
                  cy="64"
                  r="52"
                  fill="none"
                  stroke="rgb(55, 65, 81)"
                  strokeWidth="8"
                />
                <circle
                  cx="64"
                  cy="64"
                  r="52"
                  fill="none"
                  stroke="url(#gradient)"
                  strokeWidth="8"
                  strokeLinecap="round"
                  strokeDasharray={`${(stats.efficiency / 100) * 326.73} 326.73`}
                  className="transition-all duration-1000"
                />
                <defs>
                  <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" style={{ stopColor: '#06b6d4' }} />
                    <stop offset="50%" style={{ stopColor: '#a855f7' }} />
                    <stop offset="100%" style={{ stopColor: '#3b82f6' }} />
                  </linearGradient>
                </defs>
              </svg>
              <div className="absolute inset-0 flex items-center justify-center">
                <span className="text-2xl font-bold text-white">{stats.efficiency}%</span>
              </div>
            </div>
            
            <div className="text-center text-white/70">
              Уровень квантовой синхронизации
            </div>
          </div>
        </div>
      </div>
    </div>
  )
})

CosmicVariantBlock.displayName = 'CosmicVariantBlock'