import { Calendar, Clock, Star, Zap, Users, Target } from 'lucide-react'
import { memo } from 'react'

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

/**
 * Галактический вариант табеля - космическая тема с анимациями
 * 
 * Особенности:
 * - Темная космическая тема с градиентами
 * - Анимированные элементы с эффектами частиц
 * - Календарная сетка с интерактивными днями
 * - Статистика в виде космических карточек
 * - Визуализация эффективности как звездные рейтинги
 */
export const GalaxyVariantBlock = memo<GalaxyVariantBlockProps>(function GalaxyVariantBlock({
  employee,
  calendarData,
  stats,
  utils,
  selectedMonth,
  selectedYear,
}) {
  const monthName = utils.getMonthName(selectedMonth)
  const daysInMonth = utils.getDaysInMonth(selectedMonth, selectedYear)
  const firstDayOfMonth = utils.getFirstDayOfMonth(selectedMonth, selectedYear)

  // Создаем массив недель для календарной сетки
  const weeks: (number | null)[][] = []
  let currentWeek: (number | null)[] = []
  
  // Заполняем пустые дни в начале месяца
  for (let i = 0; i < firstDayOfMonth; i++) {
    currentWeek.push(null)
  }
  
  // Заполняем дни месяца
  for (let day = 1; day <= daysInMonth; day++) {
    if (currentWeek.length === 7) {
      weeks.push(currentWeek)
      currentWeek = []
    }
    currentWeek.push(day)
  }
  
  // Заполняем оставшиеся дни
  while (currentWeek.length < 7) {
    currentWeek.push(null)
  }
  weeks.push(currentWeek)

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

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

  return (
    <div className="galaxy-variant">
      {/* Заголовок с информацией о сотруднике */}
      <div className="glass-card p-6 mb-8 relative overflow-hidden">
        {/* Космический фон */}
        <div className="absolute inset-0 opacity-20">
          <div className="absolute top-4 left-8 w-1 h-1 bg-white rounded-full animate-pulse" />
          <div className="absolute top-12 left-32 w-1 h-1 bg-blue-300 rounded-full animate-pulse" style={{ animationDelay: '1s' }} />
          <div className="absolute top-6 right-16 w-1 h-1 bg-purple-300 rounded-full animate-pulse" style={{ animationDelay: '2s' }} />
        </div>

        <div className="relative z-10 flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <div className="w-16 h-16 bg-gradient-to-br from-purple-500 to-blue-600 rounded-full flex items-center justify-center">
              <Users className="w-8 h-8 text-white" />
            </div>
            <div>
              <h2 className="text-2xl font-bold text-white mb-1">🌌 {employee.name}</h2>
              <p className="text-white/70">{employee.position} • {employee.level}</p>
              <div className="flex items-center space-x-4 mt-2 text-sm text-white/60">
                <span>{employee.department}</span>
                <span>•</span>
                <span>{monthName} {selectedYear}</span>
              </div>
            </div>
          </div>
          
          {/* Статистика справа */}
          <div className="flex space-x-6">
            <div className="text-center">
              <div className="text-2xl font-bold text-white">{stats.totalHours}ч</div>
              <div className="text-xs text-white/60">Общее время</div>
            </div>
            <div className="text-center">
              <div className="flex items-center justify-center space-x-1">
                {Array.from({ length: 5 }, (_, i) => (
                  <Star 
                    key={i} 
                    className={`w-4 h-4 ${i < getStarRating(stats.efficiency) 
                      ? 'text-yellow-400 fill-current' 
                      : 'text-white/30'
                    }`} 
                  />
                ))}
              </div>
              <div className="text-xs text-white/60">Эффективность</div>
            </div>
          </div>
        </div>
      </div>

      {/* Календарная сетка */}
      <div className="glass-card p-6">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-xl font-bold text-white flex items-center space-x-2">
            <Calendar className="w-5 h-5" />
            <span>Календарь рабочего времени</span>
          </h3>
        </div>

        {/* Заголовки дней недели */}
        <div className="grid grid-cols-7 gap-2 mb-4">
          {['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'].map(day => (
            <div key={day} className="text-center text-white/70 font-medium py-2">
              {day}
            </div>
          ))}
        </div>

        {/* Календарная сетка */}
        <div className="space-y-2">
          {weeks.map((week, weekIndex) => (
            <div key={weekIndex} className="grid grid-cols-7 gap-2">
              {week.map((day, dayIndex) => {
                if (!day) return <div key={dayIndex} className="h-16" />
                
                const dayData = getDayData(day)
                const isWeekend = (firstDayOfMonth + day - 1) % 7 === 0 || (firstDayOfMonth + day - 1) % 7 === 6
                
                return (
                  <div 
                    key={day} 
                    className={`
                      relative h-16 rounded-lg border-2 transition-all duration-300 cursor-pointer
                      hover:scale-105 hover:z-10 group
                      ${dayData ? utils.getStatusColor(dayData.status) : 'bg-white/5 border-white/10'}
                      ${isWeekend ? 'bg-purple-900/20' : ''}
                    `}
                  >
                    {/* Номер дня */}
                    <div className="absolute top-1 left-2 text-sm font-bold">
                      {day}
                    </div>
                    
                    {/* Часы работы */}
                    {dayData && dayData.hours > 0 && (
                      <div className="absolute top-1 right-2 text-xs flex items-center space-x-1">
                        <Clock className="w-3 h-3" />
                        <span>{dayData.hours}ч</span>
                      </div>
                    )}
                    
                    {/* Эффективность как звезды */}
                    {dayData && dayData.efficiency !== null && (
                      <div className="absolute bottom-1 left-1 flex space-x-0.5">
                        {Array.from({ length: 3 }, (_, i) => (
                          <Star 
                            key={i} 
                            className={`w-2 h-2 ${i < Math.ceil(dayData.efficiency! / 35) 
                              ? 'text-yellow-400 fill-current' 
                              : 'text-white/20'
                            }`} 
                          />
                        ))}
                      </div>
                    )}

                    {/* Переработки */}
                    {dayData && dayData.overtime > 0 && (
                      <div className="absolute bottom-1 right-1">
                        <Zap className="w-3 h-3 text-orange-400" />
                      </div>
                    )}

                    {/* Tooltip при наведении */}
                    <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">
                      <div className="bg-black/90 text-white text-xs rounded-lg px-3 py-2 whitespace-nowrap">
                        {dayData ? (
                          <>
                            <div>День {day}: {utils.formatHours(dayData.hours)}</div>
                            {dayData.overtime > 0 && <div>Переработка: +{utils.formatHours(dayData.overtime)}</div>}
                            {dayData.efficiency !== null && <div>Эффективность: {dayData.efficiency}%</div>}
                            <div>Задач: {dayData.tasks}</div>
                          </>
                        ) : (
                          <div>День {day}: без данных</div>
                        )}
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          ))}
        </div>
      </div>

      {/* Детальная статистика */}
      <div className="mt-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div className="glass-card p-6 relative overflow-hidden">
          <div className="absolute top-4 right-4 opacity-30">
            <Target className="w-8 h-8 text-blue-400" />
          </div>
          <div className="relative z-10">
            <div className="text-2xl font-bold text-white mb-1">{stats.completedTasks}</div>
            <div className="text-white/70">Выполнено задач</div>
            <div className="text-xs text-green-400 mt-2">
              {stats.averageHoursPerDay}ч в среднем
            </div>
          </div>
        </div>

        <div className="glass-card p-6 relative overflow-hidden">
          <div className="absolute top-4 right-4 opacity-30">
            <Zap className="w-8 h-8 text-orange-400" />
          </div>
          <div className="relative z-10">
            <div className="text-2xl font-bold text-white mb-1">{stats.overtime}ч</div>
            <div className="text-white/70">Переработки</div>
            <div className="text-xs text-orange-400 mt-2">
              {stats.weekendWork} выходных дней
            </div>
          </div>
        </div>

        <div className="glass-card p-6 relative overflow-hidden">
          <div className="absolute top-4 right-4 opacity-30">
            <Star className="w-8 h-8 text-yellow-400" />
          </div>
          <div className="relative z-10">
            <div className="text-2xl font-bold text-white mb-1">{stats.efficiency}%</div>
            <div className="text-white/70">Эффективность</div>
            <div className="flex space-x-1 mt-2">
              {Array.from({ length: 5 }, (_, i) => (
                <Star 
                  key={i} 
                  className={`w-3 h-3 ${i < getStarRating(stats.efficiency) 
                    ? 'text-yellow-400 fill-current' 
                    : 'text-white/20'
                  }`} 
                />
              ))}
            </div>
          </div>
        </div>

        <div className="glass-card p-6 relative overflow-hidden">
          <div className="absolute top-4 right-4 opacity-30">
            <Users className="w-8 h-8 text-purple-400" />
          </div>
          <div className="relative z-10">
            <div className="text-2xl font-bold text-white mb-1">{stats.projects}</div>
            <div className="text-white/70">Проектов</div>
            <div className="text-xs text-purple-400 mt-2">
              Активных проектов
            </div>
          </div>
        </div>
      </div>
    </div>
  )
})

GalaxyVariantBlock.displayName = 'GalaxyVariantBlock'