import { Play, Pause, Edit3, Save, X, Plus, Minus, Target, Award, Coffee } from 'lucide-react'
import { memo, useState, useCallback } from 'react'

import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

import type { InteractiveVariantBlockProps, CalendarDay } from '../types'

/**
 * Интерактивный вариант табеля - с возможностью редактирования
 * 
 * Особенности:
 * - Редактирование данных в реальном времени
 * - Drag & Drop для изменения часов
 * - Модальные окна для детального редактирования
 * - Анимации и интерактивные элементы
 * - Сохранение изменений с валидацией
 */
export const InteractiveVariantBlock = memo<InteractiveVariantBlockProps>(function InteractiveVariantBlock({
  employee,
  calendarData,
  stats,
  utils,
  selectedMonth,
  selectedYear,
  onUpdateDay,
}) {
  const [editingDay, setEditingDay] = useState<number | null>(null)
  const [editData, setEditData] = useState<Partial<CalendarDay>>({})
  const [isTimerRunning, setIsTimerRunning] = useState(false)
  const [currentHours] = useState(0)
  
  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 handleEditStart = useCallback((day: number) => {
    const dayData = getDayData(day)
    setEditingDay(day)
    setEditData(dayData || {
      day,
      status: 'work',
      hours: 0,
      overtime: 0,
      workType: 'office',
      mood: 'normal',
      efficiency: 75,
      tasks: 0,
      breaks: 0,
    })
  }, [calendarData, getDayData])

  const handleEditSave = useCallback(() => {
    if (editingDay && onUpdateDay) {
      onUpdateDay(editingDay, editData as CalendarDay)
    }
    setEditingDay(null)
    setEditData({})
  }, [editingDay, editData, onUpdateDay])

  const handleEditCancel = useCallback(() => {
    setEditingDay(null)
    setEditData({})
  }, [])

  const handleQuickHoursChange = useCallback((day: number, delta: number) => {
    if (onUpdateDay) {
      const dayData = getDayData(day)
      const newHours = Math.max(0, Math.min(16, (dayData?.hours || 0) + delta))
      onUpdateDay(day, {
        ...dayData,
        day,
        hours: newHours,
        status: newHours > 0 ? 'work' : 'weekend',
        efficiency: dayData?.efficiency || 75,
        tasks: dayData?.tasks || 0,
        breaks: dayData?.breaks || 0,
        overtime: dayData?.overtime || 0,
        workType: dayData?.workType || 'office',
        mood: dayData?.mood || 'normal',
      })
    }
  }, [calendarData, onUpdateDay, getDayData])

  const getInteractiveStyle = (hours: number, overtime: number) => {
    const total = hours + overtime
    if (total === 0) return 'bg-gray-600/20 hover:bg-gray-600/40'
    if (total <= 4) return 'bg-blue-500/30 hover:bg-blue-500/50'
    if (total <= 8) return 'bg-green-500/30 hover:bg-green-500/50'
    if (total <= 10) return 'bg-yellow-500/30 hover:bg-yellow-500/50'
    return 'bg-red-500/30 hover:bg-red-500/50'
  }

  const renderEditModal = () => {
    if (!editingDay) return null

    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
        <div className="bg-gray-900 rounded-lg p-6 w-full max-w-md border border-white/20">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-bold text-white">
              Редактирование дня {editingDay}
            </h3>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleEditCancel}
              className="text-white/60 hover:text-white"
            >
              <X className="w-4 h-4" />
            </Button>
          </div>

          <div className="space-y-4">
            <div>
              <label className="block text-white/70 text-sm mb-2">Статус</label>
              <Select
                value={editData.status || 'work'}
                onValueChange={(value) => setEditData({ ...editData, status: value as CalendarDay['status'] })}
              >
                <SelectTrigger className="bg-white/10 border-white/20 text-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-gray-900 border-white/20">
                  <SelectItem value="work">🏢 Работа в офисе</SelectItem>
                  <SelectItem value="remote">🏠 Удаленная работа</SelectItem>
                  <SelectItem value="business">✈️ Командировка</SelectItem>
                  <SelectItem value="vacation">🏖️ Отпуск</SelectItem>
                  <SelectItem value="sick">🤒 Больничный</SelectItem>
                  <SelectItem value="weekend">📅 Выходной</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-white/70 text-sm mb-2">Часы работы</label>
                <Input
                  type="number"
                  min="0"
                  max="16"
                  value={editData.hours || 0}
                  onChange={(e) => setEditData({ ...editData, hours: Number(e.target.value) })}
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
              
              <div>
                <label className="block text-white/70 text-sm mb-2">Переработки</label>
                <Input
                  type="number"
                  min="0"
                  max="8"
                  value={editData.overtime || 0}
                  onChange={(e) => setEditData({ ...editData, overtime: Number(e.target.value) })}
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-white/70 text-sm mb-2">Эффективность (%)</label>
                <Input
                  type="number"
                  min="0"
                  max="100"
                  value={editData.efficiency || 75}
                  onChange={(e) => setEditData({ ...editData, efficiency: Number(e.target.value) })}
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
              
              <div>
                <label className="block text-white/70 text-sm mb-2">Задач выполнено</label>
                <Input
                  type="number"
                  min="0"
                  max="20"
                  value={editData.tasks || 0}
                  onChange={(e) => setEditData({ ...editData, tasks: Number(e.target.value) })}
                  className="bg-white/10 border-white/20 text-white"
                />
              </div>
            </div>

            <div>
              <label className="block text-white/70 text-sm mb-2">Настроение</label>
              <Select
                value={editData.mood || 'normal'}
                onValueChange={(value) => setEditData({ ...editData, mood: value as CalendarDay['mood'] })}
              >
                <SelectTrigger className="bg-white/10 border-white/20 text-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-gray-900 border-white/20">
                  <SelectItem value="excellent">😄 Отлично</SelectItem>
                  <SelectItem value="good">😊 Хорошо</SelectItem>
                  <SelectItem value="normal">😐 Нормально</SelectItem>
                  <SelectItem value="tired">😴 Устал</SelectItem>
                  <SelectItem value="bad">😞 Плохо</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="flex space-x-3 mt-6">
            <Button
              onClick={handleEditSave}
              className="flex-1 bg-green-600 hover:bg-green-700 text-white"
            >
              <Save className="w-4 h-4 mr-2" />
              Сохранить
            </Button>
            <Button
              variant="outline"
              onClick={handleEditCancel}
              className="flex-1 border-white/30 text-white hover:bg-white/10"
            >
              Отмена
            </Button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="interactive-variant">
      {/* Заголовок с интерактивными элементами */}
      <div className="glass-card p-6 mb-8">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-2xl font-bold text-white mb-1">
              🎯 {employee.name} - Интерактивный режим
            </h2>
            <p className="text-white/70">
              {employee.position} • {monthName} {selectedYear}
            </p>
          </div>

          {/* Мини таймер */}
          <div className="flex items-center space-x-4">
            <div className="text-center">
              <div className="text-2xl font-mono text-white">
                {Math.floor(currentHours)}:{String(Math.floor((currentHours % 1) * 60)).padStart(2, '0')}
              </div>
              <div className="text-xs text-white/60">Текущая сессия</div>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsTimerRunning(!isTimerRunning)}
              className="text-white border-white/30"
            >
              {isTimerRunning ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
            </Button>
          </div>
        </div>

        {/* Интерактивная статистика */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="text-center p-3 bg-blue-500/20 rounded-lg border border-blue-500/30">
            <div className="text-xl font-bold text-blue-400">{stats.totalHours}ч</div>
            <div className="text-white/60 text-sm">Общее время</div>
          </div>
          <div className="text-center p-3 bg-green-500/20 rounded-lg border border-green-500/30">
            <div className="text-xl font-bold text-green-400">{stats.completedTasks}</div>
            <div className="text-white/60 text-sm">Задач</div>
          </div>
          <div className="text-center p-3 bg-purple-500/20 rounded-lg border border-purple-500/30">
            <div className="text-xl font-bold text-purple-400">{stats.efficiency}%</div>
            <div className="text-white/60 text-sm">Эффективность</div>
          </div>
          <div className="text-center p-3 bg-orange-500/20 rounded-lg border border-orange-500/30">
            <div className="text-xl font-bold text-orange-400">{stats.overtime}ч</div>
            <div className="text-white/60 text-sm">Переработки</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">Календарь с редактированием</h3>
          <div className="text-sm text-white/60">
            Нажмите на день для редактирования, используйте +/- для быстрого изменения часов
          </div>
        </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-20" />
                
                const dayData = getDayData(day)
                const totalHours = (dayData?.hours || 0) + (dayData?.overtime || 0)
                
                return (
                  <div 
                    key={day}
                    className={`
                      relative h-20 rounded-lg border-2 transition-all duration-300 cursor-pointer
                      ${getInteractiveStyle(dayData?.hours || 0, dayData?.overtime || 0)}
                      hover:scale-105 hover:border-white/50 group
                    `}
                    onClick={() => handleEditStart(day)}
                  >
                    {/* Номер дня */}
                    <div className="absolute top-1 left-2 text-sm font-bold text-white">
                      {day}
                    </div>

                    {/* Часы работы */}
                    {dayData && totalHours > 0 && (
                      <div className="absolute top-1 right-2 text-xs text-white/90 font-medium">
                        {totalHours}ч
                      </div>
                    )}

                    {/* Настроение */}
                    {dayData && dayData.mood && (
                      <div className="absolute top-6 left-2 text-lg">
                        {dayData.mood === 'excellent' && '😄'}
                        {dayData.mood === 'good' && '😊'}
                        {dayData.mood === 'normal' && '😐'}
                        {dayData.mood === 'tired' && '😴'}
                        {dayData.mood === 'bad' && '😞'}
                      </div>
                    )}

                    {/* Эффективность */}
                    {dayData && dayData.efficiency !== null && (
                      <div className="absolute bottom-1 left-2 text-xs text-white/70">
                        {dayData.efficiency}%
                      </div>
                    )}

                    {/* Быстрые кнопки +/- */}
                    <div className="absolute bottom-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity flex space-x-1">
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          handleQuickHoursChange(day, -1)
                        }}
                        className="w-4 h-4 bg-red-500/80 rounded-full flex items-center justify-center hover:bg-red-500"
                      >
                        <Minus className="w-2 h-2 text-white" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          handleQuickHoursChange(day, 1)
                        }}
                        className="w-4 h-4 bg-green-500/80 rounded-full flex items-center justify-center hover:bg-green-500"
                      >
                        <Plus className="w-2 h-2 text-white" />
                      </button>
                    </div>

                    {/* Индикатор редактирования */}
                    <div className="absolute -top-1 -right-1 opacity-0 group-hover:opacity-100 transition-opacity">
                      <div className="w-4 h-4 bg-blue-500 rounded-full flex items-center justify-center">
                        <Edit3 className="w-2 h-2 text-white" />
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          ))}
        </div>
      </div>

      {/* Интерактивные достижения */}
      <div className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="glass-card p-6">
          <div className="flex items-center space-x-3 mb-4">
            <Target className="w-6 h-6 text-blue-400" />
            <h4 className="text-lg font-bold text-white">Цели</h4>
          </div>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-white/70">Месячная норма:</span>
              <span className={`font-bold ${stats.totalHours >= 160 ? 'text-green-400' : 'text-white'}`}>
                {stats.totalHours}/160ч
              </span>
            </div>
            <div className="w-full bg-white/10 rounded-full h-2">
              <div 
                className="bg-blue-500 h-2 rounded-full transition-all duration-500"
                style={{ width: `${Math.min((stats.totalHours / 160) * 100, 100)}%` }}
              />
            </div>
          </div>
        </div>

        <div className="glass-card p-6">
          <div className="flex items-center space-x-3 mb-4">
            <Award className="w-6 h-6 text-yellow-400" />
            <h4 className="text-lg font-bold text-white">Достижения</h4>
          </div>
          <div className="space-y-2 text-sm">
            {stats.efficiency >= 90 && (
              <div className="text-green-400">🏆 Высокая эффективность</div>
            )}
            {stats.completedTasks >= 50 && (
              <div className="text-blue-400">⚡ Продуктивный месяц</div>
            )}
            {stats.overtime <= 5 && (
              <div className="text-purple-400">🎯 Баланс work-life</div>
            )}
          </div>
        </div>

        <div className="glass-card p-6">
          <div className="flex items-center space-x-3 mb-4">
            <Coffee className="w-6 h-6 text-orange-400" />
            <h4 className="text-lg font-bold text-white">Wellness</h4>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-orange-400">
              {Math.round(stats.averageHoursPerDay * 10) / 10}ч
            </div>
            <div className="text-white/60 text-sm">Среднее в день</div>
            <div className="mt-2 text-xs text-white/50">
              Рекомендуется: 8ч
            </div>
          </div>
        </div>
      </div>

      {/* Модальное окно редактирования */}
      {renderEditModal()}
    </div>
  )
})

InteractiveVariantBlock.displayName = 'InteractiveVariantBlock'