"use client"

import { useState } from 'react'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { 
  Calendar,
  ChevronLeft,
  ChevronRight,

  CheckCircle,
  XCircle,
  Plane,
  Activity,
  Clock
} from 'lucide-react'

// Типы для табеля
type WorkDayStatus = 'work' | 'weekend' | 'vacation' | 'sick' | 'absent'

interface WorkDay {
  date: Date
  status: WorkDayStatus
  hours?: number
  note?: string
}

interface EmployeeSchedule {
  employeeId: string
  month: string
  year: number
  days: WorkDay[]
}

interface Employee {
  id: string
  firstName: string
  lastName: string
  position: string
  department?: string
  phone: string
  email: string
  avatar?: string
  hireDate: string
  status: 'active' | 'vacation' | 'sick' | 'inactive'
  salary: number
  address: string
}

interface EmployeeScheduleProps {
  employees: Employee[]
}

export function EmployeeSchedule({ employees }: EmployeeScheduleProps) {
  const [currentDate, setCurrentDate] = useState(new Date())
  const [selectedEmployee, setSelectedEmployee] = useState<string>('all')
  const [schedules, setSchedules] = useState<Record<string, EmployeeSchedule>>({})

  // Получаем текущий месяц и год
  const currentMonth = currentDate.getMonth()
  const currentYear = currentDate.getFullYear()
  
  // Получаем количество дней в месяце
  const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate()
  const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay()
  
  // Массив дней недели
  const weekDays = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']
  
  // Названия месяцев
  const monthNames = [
    'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
    'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
  ]

  // Функции навигации
  const goToPrevMonth = () => {
    setCurrentDate(new Date(currentYear, currentMonth - 1, 1))
  }

  const goToNextMonth = () => {
    setCurrentDate(new Date(currentYear, currentMonth + 1, 1))
  }

  const goToToday = () => {
    setCurrentDate(new Date())
  }

  // Получить статус работы для конкретного дня и сотрудника
  const getDayStatus = (employeeId: string, day: number): WorkDayStatus => {
    const monthKey = `${currentYear}-${currentMonth}`
    const schedule = schedules[`${employeeId}-${monthKey}`]
    if (!schedule) return getDefaultStatus(day)
    
    const dayData = schedule.days.find(d => d.date.getDate() === day)
    return dayData?.status || getDefaultStatus(day)
  }

  // Получить количество часов для дня
  const getDayHours = (employeeId: string, day: number): number => {
    const monthKey = `${currentYear}-${currentMonth}`
    const schedule = schedules[`${employeeId}-${monthKey}`]
    if (!schedule) return getDefaultHours(day)
    
    const dayData = schedule.days.find(d => d.date.getDate() === day)
    return dayData?.hours || getDefaultHours(day)
  }

  // Получить стандартный статус для дня (выходные или рабочие дни)
  const getDefaultStatus = (day: number): WorkDayStatus => {
    const date = new Date(currentYear, currentMonth, day)
    const dayOfWeek = date.getDay()
    return (dayOfWeek === 0 || dayOfWeek === 6) ? 'weekend' : 'work'
  }

  // Получить стандартное количество часов
  const getDefaultHours = (day: number): number => {
    const status = getDefaultStatus(day)
    return status === 'work' ? 8 : 0
  }

  // Изменить статус дня для сотрудника
  const changeDayStatus = (employeeId: string, day: number, status: WorkDayStatus) => {
    const monthKey = `${currentYear}-${currentMonth}`
    const scheduleKey = `${employeeId}-${monthKey}`
    const date = new Date(currentYear, currentMonth, day)
    
    setSchedules(prev => {
      const currentSchedule = prev[scheduleKey] || {
        employeeId,
        month: monthKey,
        year: currentYear,
        days: []
      }
      
      const existingDayIndex = currentSchedule.days.findIndex(d => d.date.getDate() === day)
      const hours = status === 'work' ? 8 : status === 'vacation' || status === 'sick' ? 8 : 0
      
      if (existingDayIndex >= 0) {
        currentSchedule.days[existingDayIndex] = {
          ...currentSchedule.days[existingDayIndex],
          status,
          hours
        }
      } else {
        currentSchedule.days.push({
          date,
          status,
          hours
        })
      }
      
      return {
        ...prev,
        [scheduleKey]: currentSchedule
      }
    })
  }

  // Получить стиль ячейки в зависимости от статуса
  const getCellStyle = (status: WorkDayStatus) => {
    switch (status) {
      case 'work':
        return 'bg-emerald-500/20 text-emerald-300/70 border-emerald-400/80'
      case 'weekend':
        return 'bg-purple-500/20 text-purple-300/70 border-purple-400/80'
      case 'vacation':
        return 'bg-blue-500/20 text-blue-300/70 border-blue-400/80'
      case 'sick':
        return 'bg-yellow-500/20 text-yellow-300/70 border-yellow-400/80'
      case 'absent':
        return 'bg-red-500/20 text-red-300/70 border-red-400/80'
      default:
        return 'bg-white/10 text-white/50 border-white/20'
    }
  }

  // Получить иконку для статуса
  const getStatusIcon = (status: WorkDayStatus) => {
    switch (status) {
      case 'work':
        return <CheckCircle className="h-3 w-3" />
      case 'weekend':
        return <Clock className="h-3 w-3" />
      case 'vacation':
        return <Plane className="h-3 w-3" />
      case 'sick':
        return <Activity className="h-3 w-3" />
      case 'absent':
        return <XCircle className="h-3 w-3" />
      default:
        return null
    }
  }

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

  // Создаем массив дней для отображения
  const calendarDays: (number | null)[] = []
  
  // Добавляем пустые ячейки для выравнивания первой недели
  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)
  }

  // Получить статистику для сотрудника за месяц
  const getMonthStats = (employeeId: string) => {
    // const monthKey = `${currentYear}-${currentMonth}`
    // const schedule = schedules[`${employeeId}-${monthKey}`]
    
    let workDays = 0
    let vacationDays = 0
    let sickDays = 0
    let absentDays = 0
    let totalHours = 0
    
    for (let day = 1; day <= daysInMonth; day++) {
      const status = getDayStatus(employeeId, day)
      const hours = getDayHours(employeeId, day)
      
      switch (status) {
        case 'work':
          workDays++
          break
        case 'vacation':
          vacationDays++
          break
        case 'sick':
          sickDays++
          break
        case 'absent':
          absentDays++
          break
      }
      
      totalHours += hours
    }
    
    return { workDays, vacationDays, sickDays, absentDays, totalHours }
  }

  return (
    <div className="space-y-6">
      {/* Заголовок с навигацией */}
      <Card className="glass-card p-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              size="sm"
              onClick={goToPrevMonth}
              className="glass-secondary text-white hover:text-white"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            
            <h2 className="text-xl font-semibold text-white">
              {monthNames[currentMonth]} {currentYear}
            </h2>
            
            <Button
              variant="outline"
              size="sm"
              onClick={goToNextMonth}
              className="glass-secondary text-white hover:text-white"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>

          <div className="flex items-center gap-4">
            <Button
              variant="outline"
              size="sm"
              onClick={goToToday}
              className="glass-secondary text-white hover:text-white"
            >
              <Calendar className="h-4 w-4 mr-2" />
              Сегодня
            </Button>
            
            <Select value={selectedEmployee} onValueChange={setSelectedEmployee}>
              <SelectTrigger className="glass-input text-white w-48">
                <SelectValue />
              </SelectTrigger>
              <SelectContent className="bg-gray-900 border-white/20">
                <SelectItem value="all" className="text-white hover:bg-white/10">
                  Все сотрудники
                </SelectItem>
                {employees.map(emp => (
                  <SelectItem key={emp.id} value={emp.id} className="text-white hover:bg-white/10">
                    {emp.firstName} {emp.lastName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* Легенда */}
        <div className="flex flex-wrap gap-3">
          {[
            { status: 'work' as WorkDayStatus, label: 'Рабочий день' },
            { status: 'weekend' as WorkDayStatus, label: 'Выходной' },
            { status: 'vacation' as WorkDayStatus, label: 'Отпуск' },
            { status: 'sick' as WorkDayStatus, label: 'Больничный' },
            { status: 'absent' as WorkDayStatus, label: 'Прогул' }
          ].map(({ status, label }) => (
            <div key={status} className="flex items-center gap-2">
              <div className={`w-4 h-4 rounded border ${getCellStyle(status)}`}>
                {getStatusIcon(status)}
              </div>
              <span className="text-white/70 text-sm">{label}</span>
            </div>
          ))}
        </div>
      </Card>

      {/* Календарь для каждого сотрудника */}
      {(selectedEmployee === 'all' ? employees : employees.filter(e => e.id === selectedEmployee)).map(employee => {
        const stats = getMonthStats(employee.id)
        
        return (
          <Card key={employee.id} className="glass-card p-6">
            {/* Информация о сотруднике */}
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                <Avatar className="h-12 w-12 ring-2 ring-white/20">
                  {employee.avatar ? (
                    <AvatarImage src={employee.avatar} alt={`${employee.firstName} ${employee.lastName}`} />
                  ) : null}
                  <AvatarFallback className="bg-gradient-to-br from-purple-500 to-purple-600 text-white font-semibold">
                    {employee.firstName.charAt(0)}{employee.lastName.charAt(0)}
                  </AvatarFallback>
                </Avatar>
                <div>
                  <h3 className="text-white font-semibold text-lg">{employee.firstName} {employee.lastName}</h3>
                  <p className="text-white/70 text-sm">Табель работы за {monthNames[currentMonth].toLowerCase()}</p>
                </div>
              </div>
              
              {/* Статистика */}
              <div className="grid grid-cols-2 md:grid-cols-5 gap-4 text-center">
                <div>
                  <p className="text-green-400 font-semibold text-lg">{stats.workDays}</p>
                  <p className="text-white/60 text-xs">Рабочих</p>
                </div>
                <div>
                  <p className="text-blue-400 font-semibold text-lg">{stats.vacationDays}</p>
                  <p className="text-white/60 text-xs">Отпуск</p>
                </div>
                <div>
                  <p className="text-yellow-400 font-semibold text-lg">{stats.sickDays}</p>
                  <p className="text-white/60 text-xs">Больничный</p>
                </div>
                <div>
                  <p className="text-red-400 font-semibold text-lg">{stats.absentDays}</p>
                  <p className="text-white/60 text-xs">Прогулы</p>
                </div>
                <div>
                  <p className="text-white font-semibold text-lg">{stats.totalHours}ч</p>
                  <p className="text-white/60 text-xs">Всего часов</p>
                </div>
              </div>
            </div>

            {/* Сетка календаря */}
            <div className="grid grid-cols-7 gap-2">
              {/* Заголовки дней недели */}
              {weekDays.map(day => (
                <div key={day} className="p-2 text-center text-white/70 font-medium text-sm">
                  {day}
                </div>
              ))}
              
              {/* Дни месяца */}
              {calendarDays.map((day, index) => {
                if (day === null) {
                  return <div key={`empty-${index}`} className="p-2"></div>
                }
                
                const status = getDayStatus(employee.id, day)
                const hours = getDayHours(employee.id, day)
                const isToday = new Date().getDate() === day && 
                               new Date().getMonth() === currentMonth && 
                               new Date().getFullYear() === currentYear
                
                return (
                  <div
                    key={`${employee.id}-${day}`}
                    className={`
                      relative p-2 min-h-[60px] border rounded-lg cursor-pointer
                      transition-all duration-200 hover:scale-105
                      ${getCellStyle(status)}
                      ${isToday ? 'ring-2 ring-white/50' : ''}
                    `}
                    onClick={() => {
                      // Циклично переключаем статусы
                      const statuses: WorkDayStatus[] = ['work', 'weekend', 'vacation', 'sick', 'absent']
                      const currentIndex = statuses.indexOf(status)
                      const nextStatus = statuses[(currentIndex + 1) % statuses.length]
                      changeDayStatus(employee.id, day, nextStatus)
                    }}
                  >
                    <div className="flex flex-col items-center justify-center h-full">
                      <div className="flex items-center gap-1 mb-1">
                        {getStatusIcon(status)}
                        <span className="font-semibold text-sm">{day}</span>
                      </div>
                      {hours > 0 && (
                        <span className="text-xs opacity-80">{hours}ч</span>
                      )}
                    </div>
                    
                    {isToday && (
                      <div className="absolute -top-1 -right-1 w-3 h-3 bg-white rounded-full"></div>
                    )}
                  </div>
                )
              })}
            </div>
          </Card>
        )
      })}
    </div>
  )
} 