'use client'

import { Calendar } from 'lucide-react'
import { useState } from 'react'

import { BulkEditModal } from './bulk-edit-modal'
import { DayEditModal } from './day-edit-modal'

interface ScheduleRecord {
  id: string
  date: string
  status: string
  hoursWorked?: number
  overtimeHours?: number
  notes?: string
  employee: {
    id: string
    firstName: string
    lastName: string
  }
}

interface EmployeeCalendarProps {
  employeeId: string
  employeeSchedules: { [key: string]: ScheduleRecord[] }
  currentYear: number
  currentMonth: number
  onDayStatusChange: (employeeId: string, day: number, currentStatus: string) => void
  onDayUpdate: (
    employeeId: string,
    date: Date,
    data: {
      status: string
      hoursWorked?: number
      overtimeHours?: number
      notes?: string
    },
  ) => void
  employeeName: string
}

export function EmployeeCalendar({
  employeeId,
  employeeSchedules,
  currentYear,
  currentMonth,
  onDayStatusChange: _onDayStatusChange,
  onDayUpdate,
  employeeName,
}: EmployeeCalendarProps) {
  const [selectedDate, setSelectedDate] = useState<Date | null>(null)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [selectionMode, setSelectionMode] = useState(false)
  const [selectedDates, setSelectedDates] = useState<Date[]>([])
  const [selectionStart, setSelectionStart] = useState<Date | null>(null)
  const [isBulkModalOpen, setIsBulkModalOpen] = useState(false)
  // Получаем количество дней в месяце
  const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate()

  // Функция для получения статуса дня
  const getDayStatus = (day: number) => {
    const date = new Date(currentYear, currentMonth, day)
    const dateStr = date.toISOString().split('T')[0] // YYYY-MM-DD

    // Ищем запись в табеле для этого дня
    const scheduleData = employeeSchedules[employeeId] || []
    const dayRecord = scheduleData.find((record) => record.date.split('T')[0] === dateStr)

    if (dayRecord) {
      return dayRecord.status.toLowerCase()
    }

    // Если записи нет, устанавливаем дефолтный статус с вариативностью
    const dayOfWeek = date.getDay()
    if (dayOfWeek === 0 || dayOfWeek === 6) return 'weekend'

    // Добавляем немного разнообразия для демонстрации всех статусов
    const random = Math.random()
    if (day === 15 && random > 0.7) return 'vacation' // Отпуск
    if (day === 22 && random > 0.8) return 'sick' // Больничный
    if (day === 10 && random > 0.9) return 'absent' // Прогул

    return 'work' // По умолчанию рабочий день
  }

  // Функция для получения данных дня
  const getDayData = (day: number) => {
    const date = new Date(currentYear, currentMonth, day)
    const dateStr = date.toISOString().split('T')[0]

    const scheduleData = employeeSchedules[employeeId] || []
    const dayRecord = scheduleData.find((record) => record.date.split('T')[0] === dateStr)

    return {
      status: dayRecord?.status || 'WORK',
      hoursWorked: dayRecord?.hoursWorked || 8,
      overtimeHours: dayRecord?.overtimeHours || 0,
      notes: dayRecord?.notes || '',
    }
  }

  // Обработчик клика по дню
  const handleDayClick = (day: number, _event?: React.MouseEvent) => {
    const date = new Date(currentYear, currentMonth, day)

    if (selectionMode) {
      // Режим выделения диапазона
      if (!selectionStart) {
        // Начинаем выделение
        setSelectionStart(date)
        setSelectedDates([date])
      } else {
        // Завершаем выделение диапазона
        const startDay = selectionStart.getDate()
        const endDay = day
        const start = Math.min(startDay, endDay)
        const end = Math.max(startDay, endDay)

        const rangeDates: Date[] = []
        for (let d = start; d <= end; d++) {
          rangeDates.push(new Date(currentYear, currentMonth, d))
        }

        setSelectedDates(rangeDates)
        setIsBulkModalOpen(true)
      }
    } else {
      // Обычный режим - одиночное редактирование
      setSelectedDate(date)
      setIsModalOpen(true)
    }
  }

  // Проверка, выделена ли дата
  const isDateSelected = (day: number) => {
    return selectedDates.some((date) => date.getDate() === day)
  }

  // Переключение режима выделения
  const toggleSelectionMode = () => {
    setSelectionMode(!selectionMode)
    setSelectedDates([])
    setSelectionStart(null)
  }

  // Очистка выделения
  const clearSelection = () => {
    setSelectedDates([])
    setSelectionStart(null)
  }

  // Обработчик сохранения данных дня
  const handleDaySave = (data: { status: string; hoursWorked?: number; overtimeHours?: number; notes?: string }) => {
    if (selectedDate) {
      onDayUpdate(employeeId, selectedDate, data)
    }
  }

  // Обработчик массового сохранения
  const handleBulkSave = (data: { status: string; hoursWorked?: number; overtimeHours?: number; notes?: string }) => {
    selectedDates.forEach((date) => {
      onDayUpdate(employeeId, date, data)
    })

    // Очищаем выделение после сохранения
    clearSelection()
    setSelectionMode(false)
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'work':
        return 'Рабочий день'
      case 'weekend':
        return 'Выходной'
      case 'vacation':
        return 'Отпуск'
      case 'sick':
        return 'Больничный'
      case 'absent':
        return 'Прогул'
      default:
        return 'Не определен'
    }
  }

  // Создаем массив дней календаря
  const calendarDays: (number | null)[] = []
  const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay()
  const startOffset = firstDayOfMonth === 0 ? 6 : firstDayOfMonth - 1

  // Добавляем пустые ячейки для выравнивания первой недели
  for (let i = 0; i < startOffset; i++) {
    calendarDays.push(null)
  }

  // Добавляем дни месяца
  for (let day = 1; day <= daysInMonth; day++) {
    calendarDays.push(day)
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between mb-2">
        <h4 className="text-white/80 font-medium flex items-center gap-2 text-xs">
          <Calendar className="h-3 w-3" />
          Табель за {new Date(currentYear, currentMonth).toLocaleDateString('ru-RU', { month: 'long' })}
        </h4>

        {/* Кнопки управления выделением */}
        <div className="flex items-center gap-2">
          {selectionMode && selectedDates.length > 0 && (
            <span className="text-xs text-white/60">
              Выбрано: {selectedDates.length} {selectedDates.length === 1 ? 'день' : 'дней'}
            </span>
          )}

          <button
            onClick={toggleSelectionMode}
            className={`text-xs px-2 py-1 rounded transition-colors ${
              selectionMode
                ? 'bg-purple-500/20 text-purple-300 border border-purple-400/40'
                : 'text-white/60 hover:text-white hover:bg-white/10'
            }`}
          >
            {selectionMode ? 'Отмена' : 'Выделить'}
          </button>

          {selectionMode && selectedDates.length > 0 && (
            <button
              onClick={clearSelection}
              className="text-xs px-2 py-1 rounded text-red-300 hover:text-red-200 hover:bg-red-500/10"
            >
              Очистить
            </button>
          )}
        </div>
      </div>

      {/* Компактная календарная сетка */}
      <div className="space-y-2">
        {/* Заголовки дней недели */}
        <div className="grid grid-cols-7 gap-1 text-center text-xs text-white/70 font-medium">
          <div>ПН</div>
          <div>ВТ</div>
          <div>СР</div>
          <div>ЧТ</div>
          <div>ПТ</div>
          <div>СБ</div>
          <div>ВС</div>
        </div>

        {/* Сетка календаря */}
        <div className="grid grid-cols-7 gap-1">
          {/* Дни месяца */}
          {calendarDays.map((day, index) => {
            if (day === null) {
              return <div key={`empty-${index}`} className="p-1"></div>
            }

            const status = getDayStatus(day)
            const dayData = getDayData(day)
            const hours = dayData.hoursWorked || 0
            const overtime = dayData.overtimeHours || 0
            const isToday =
              new Date().getDate() === day &&
              new Date().getMonth() === currentMonth &&
              new Date().getFullYear() === currentYear
            const isSelected = isDateSelected(day)

            return (
              <div
                key={`${employeeId}-${day}`}
                onClick={() => handleDayClick(day)}
                className={`relative group cursor-pointer transition-all duration-300 transform hover:scale-105 ${
                  isSelected
                    ? 'bg-gradient-to-br from-purple-400/40 to-purple-600/40 border-purple-300/60 shadow-lg shadow-purple-500/20 ring-1 ring-purple-400/30'
                    : status === 'work'
                      ? 'bg-gradient-to-br from-emerald-400/30 to-green-400/30 border-emerald-400/50 hover:border-emerald-300/70 shadow-lg shadow-emerald-500/20'
                      : status === 'weekend'
                        ? 'bg-gradient-to-br from-slate-400/30 to-gray-400/30 border-slate-400/50 hover:border-slate-300/70 shadow-lg shadow-slate-500/20'
                        : status === 'vacation'
                          ? 'bg-gradient-to-br from-blue-400/30 to-cyan-400/30 border-blue-400/50 hover:border-blue-300/70 shadow-lg shadow-blue-500/20'
                          : status === 'sick'
                            ? 'bg-gradient-to-br from-amber-400/30 to-orange-400/30 border-amber-400/50 hover:border-amber-300/70 shadow-lg shadow-amber-500/20'
                            : 'bg-gradient-to-br from-red-400/30 to-rose-400/30 border-red-400/50 hover:border-red-300/70 shadow-lg shadow-red-500/20'
                } rounded-lg border backdrop-blur-sm p-1.5 h-12`}
                title={`${day} число - ${getStatusText(status)}${hours > 0 ? ` (${hours}ч)` : ''}`}
              >
                <div className="flex flex-col items-center justify-center h-full">
                  <span className="text-white font-medium text-xs mb-0.5">{day}</span>

                  {status === 'work' && (
                    <div className="flex items-center space-x-0.5 text-xs">
                      <span className="text-white/90 text-xs">{hours}ч</span>
                      {overtime > 0 && <span className="text-yellow-300 text-xs">+{overtime}</span>}
                    </div>
                  )}

                  {status !== 'work' && status !== 'weekend' && (
                    <div className="flex justify-center">
                      <div
                        className={`w-1.5 h-1.5 rounded-full ${
                          status === 'vacation'
                            ? 'bg-gradient-to-r from-blue-400 to-cyan-400'
                            : status === 'sick'
                              ? 'bg-gradient-to-r from-amber-400 to-orange-400'
                              : 'bg-gradient-to-r from-red-400 to-rose-400'
                        }`}
                      ></div>
                    </div>
                  )}
                </div>

                {isToday && (
                  <div className="absolute top-0.5 right-0.5">
                    <div className="w-1.5 h-1.5 bg-white rounded-full"></div>
                  </div>
                )}

                {/* Индикатор интерактивности */}
                <div className="absolute top-0.5 left-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
                  <div className="w-1 h-1 bg-white/60 rounded-full animate-pulse"></div>
                </div>
              </div>
            )
          })}
        </div>
      </div>

      {/* SVG градиенты как в UI Kit */}
      <svg width="0" height="0">
        <defs>
          <linearGradient id="gradient-purple-bright" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#A855F7" />
            <stop offset="100%" stopColor="#7C3AED" />
          </linearGradient>
          <linearGradient id="gradient-green-bright" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#34D399" />
            <stop offset="100%" stopColor="#10B981" />
          </linearGradient>
          <linearGradient id="gradient-blue-bright" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#60A5FA" />
            <stop offset="100%" stopColor="#22D3EE" />
          </linearGradient>
          <linearGradient id="gradient-orange-bright" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#FB923C" />
            <stop offset="100%" stopColor="#F87171" />
          </linearGradient>
          <linearGradient id="gradient-yellow-bright" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#FBBF24" />
            <stop offset="100%" stopColor="#FB923C" />
          </linearGradient>
          <linearGradient id="gradient-pink-bright" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#F472B6" />
            <stop offset="100%" stopColor="#F87171" />
          </linearGradient>
        </defs>
      </svg>

      {/* Модалка редактирования дня */}
      {selectedDate && (
        <DayEditModal
          isOpen={isModalOpen}
          onClose={() => setIsModalOpen(false)}
          date={selectedDate}
          employeeName={employeeName}
          currentStatus={getDayData(selectedDate.getDate()).status}
          currentHours={getDayData(selectedDate.getDate()).hoursWorked}
          currentOvertime={getDayData(selectedDate.getDate()).overtimeHours}
          currentNotes={getDayData(selectedDate.getDate()).notes}
          onSave={handleDaySave}
        />
      )}

      {/* Модалка массового редактирования */}
      <BulkEditModal
        isOpen={isBulkModalOpen}
        onClose={() => {
          setIsBulkModalOpen(false)
          clearSelection()
          setSelectionMode(false)
        }}
        dates={selectedDates}
        employeeName={employeeName}
        onSave={handleBulkSave}
      />
    </div>
  )
}
