'use client'

import {
  Edit,
  UserX,
  Clock,
  CheckCircle,
  Plane,
  Heart,
  Zap,
  Activity,
  Phone,
  Mail,
  Briefcase,
  Calendar,
  MessageCircle,
} from 'lucide-react'
import { useState } from 'react'

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'

import { EmployeeCalendar } from './employee-calendar'

interface Employee {
  id: string
  firstName: string
  lastName: string
  middleName?: string
  position: string
  phone: string
  email?: string
  avatar?: string
  hireDate: string
  status: 'ACTIVE' | 'VACATION' | 'SICK' | 'FIRED'
  salary?: number
  address?: string
  birthDate?: string
  passportSeries?: string
  passportNumber?: string
  passportIssued?: string
  passportDate?: string
  emergencyContact?: string
  emergencyPhone?: string
  telegram?: string
  whatsapp?: string
  passportPhoto?: string
  createdAt: string
  updatedAt: string
}

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

interface EmployeeRowProps {
  employee: Employee
  employeeSchedules: { [key: string]: ScheduleRecord[] }
  currentYear: number
  currentMonth: number
  onEdit: (employee: Employee) => void
  onDelete: (employeeId: string) => void
  onDayStatusChange: (employeeId: string, day: number, currentStatus: string) => void
  onDayUpdate: (
    employeeId: string,
    date: Date,
    data: {
      status: string
      hoursWorked?: number
      overtimeHours?: number
      notes?: string
    },
  ) => void
  deletingEmployeeId: string | null
}

export function EmployeeRow({
  employee,
  employeeSchedules,
  currentYear,
  currentMonth,
  onEdit,
  onDelete,
  onDayStatusChange,
  onDayUpdate,
  deletingEmployeeId,
}: EmployeeRowProps) {
  const [isExpanded, setIsExpanded] = useState(false)

  const formatSalary = (salary?: number) => {
    if (!salary) return 'Не указана'
    return new Intl.NumberFormat('ru-RU').format(salary) + ' ₽'
  }

  const formatDate = (dateString?: string) => {
    if (!dateString) return 'Не указана'
    return new Date(dateString).toLocaleDateString('ru-RU')
  }

  // Подсчет статистики сотрудника как в календаре
  const calculateEmployeeStats = () => {
    const stats = {
      totalHours: 0,
      workDays: 0,
      vacation: 0,
      sick: 0,
      overtime: 0,
      kpi: 0,
    }

    // Получаем данные из employeeSchedules
    const scheduleData = employeeSchedules[employee.id] || []

    // Получаем количество дней в текущем месяце
    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate()

    // Проходим по всем дням месяца
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(currentYear, currentMonth, day)
      const dateStr = date.toISOString().split('T')[0]
      const dayOfWeek = date.getDay()

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

      if (dayRecord) {
        // Если есть запись в БД, используем её
        switch (dayRecord.status) {
          case 'WORK':
            stats.workDays++
            stats.totalHours += dayRecord.hoursWorked || 0
            stats.overtime += dayRecord.overtimeHours || 0
            break
          case 'VACATION':
            stats.vacation++
            break
          case 'SICK':
            stats.sick++
            break
        }
      } else {
        // Если записи нет, используем логику по умолчанию
        if (dayOfWeek !== 0 && dayOfWeek !== 6) {
          // Не выходные
          stats.workDays++
          stats.totalHours += 8 // По умолчанию 8 часов
        }
      }
    }

    // Расчет KPI на основе реальных данных
    const expectedWorkDays = Math.floor(daysInMonth * (5 / 7)) // Примерно 5 дней в неделю
    const expectedHours = expectedWorkDays * 8 // 8 часов в день

    if (expectedHours > 0) {
      // KPI = (фактические часы / ожидаемые часы) * 100
      // Учитываем также отсутствия по болезни (снижают KPI) и переработки (повышают)
      const baseKPI = (stats.totalHours / expectedHours) * 100

      // Штраф за больничные (каждый день -2%)
      const sickPenalty = stats.sick * 2

      // Бонус за переработки (каждый час +0.5%)
      const overtimeBonus = stats.overtime * 0.5

      // Итоговый KPI с ограничением от 0 до 100
      stats.kpi = Math.max(0, Math.min(100, Math.round(baseKPI - sickPenalty + overtimeBonus)))
    } else {
      stats.kpi = 0
    }

    return stats
  }

  const employeeStats = calculateEmployeeStats()

  return (
    <Card className="glass-card p-4 !gap-0">
      {/* Компактная строка сотрудника */}
      <div
        className="flex items-center gap-4 cursor-pointer hover:bg-white/5 rounded-lg p-2 -m-2 transition-colors"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        {/* Блок данных сотрудника - выделенный модуль */}
        <div className="flex-shrink-0 relative group">
          <div className="absolute inset-0 bg-gradient-to-r from-purple-400 to-indigo-400 rounded-lg opacity-20 group-hover:opacity-30 transition-opacity blur-sm"></div>
          <div className="relative glass-card p-2 rounded-lg border border-purple-400/40 hover:border-purple-300/60 transition-all duration-200 flex items-center gap-3 h-[84px]">
            {/* Аватар */}
            <Avatar className="h-10 w-10 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 text-xs">
                {employee.firstName.charAt(0)}
                {employee.lastName.charAt(0)}
              </AvatarFallback>
            </Avatar>

            {/* ФИО, должность и телефон */}
            <div className="flex-1 min-w-0">
              <h3 className="text-white font-bold text-sm mb-0.5 truncate">
                {employee.firstName} {employee.lastName}
              </h3>
              <p className="text-purple-200 text-xs mb-0.5 truncate">{employee.position}</p>
              <div className="flex items-center text-white/60 text-xs">
                <Phone className="h-3 w-3 mr-1 flex-shrink-0" />
                <span className="truncate">{employee.phone}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Основная информация в строку */}
        <div className="flex-1 flex items-center gap-6">
          {/* Статистика табеля - красивые карточки */}
          <div className="flex-1 grid grid-cols-6 gap-2">
            {/* Часов */}
            <div className="relative group">
              <div className="absolute inset-0 bg-gradient-to-r from-purple-400 to-indigo-400 rounded-lg opacity-20 group-hover:opacity-30 transition-opacity blur-sm"></div>
              <div className="relative glass-card p-2 rounded-lg border border-purple-400/40 hover:border-purple-300/60 transition-all duration-200 text-center">
                <div className="relative w-6 h-6 mx-auto mb-1">
                  <svg className="w-6 h-6 transform -rotate-90" viewBox="0 0 36 36">
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="rgba(255,255,255,0.15)"
                      strokeWidth={3}
                    />
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="url(#gradient-purple-bright)"
                      strokeWidth={3}
                      strokeDasharray={`${(employeeStats.totalHours / 200) * 100}, 100`}
                      strokeLinecap="round"
                    />
                  </svg>
                  <div className="absolute inset-0 flex items-center justify-center">
                    <Clock className="h-3 w-3 text-purple-300" />
                  </div>
                </div>
                <div className="text-white font-bold text-sm mb-0.5">{employeeStats.totalHours}ч</div>
                <p className="text-purple-200 text-xs">Часов</p>
              </div>
            </div>

            {/* Рабочих */}
            <div className="relative group">
              <div className="absolute inset-0 bg-gradient-to-r from-green-400 to-emerald-400 rounded-lg opacity-20 group-hover:opacity-30 transition-opacity blur-sm"></div>
              <div className="relative glass-card p-2 rounded-lg border border-green-400/40 hover:border-green-300/60 transition-all duration-200 text-center">
                <div className="relative w-6 h-6 mx-auto mb-1">
                  <svg className="w-6 h-6 transform -rotate-90" viewBox="0 0 36 36">
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="rgba(255,255,255,0.15)"
                      strokeWidth={3}
                    />
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="url(#gradient-green-bright)"
                      strokeWidth={3}
                      strokeDasharray={`${(employeeStats.workDays / 25) * 100}, 100`}
                      strokeLinecap="round"
                    />
                  </svg>
                  <div className="absolute inset-0 flex items-center justify-center">
                    <CheckCircle className="h-3 w-3 text-green-300" />
                  </div>
                </div>
                <div className="text-white font-bold text-sm mb-0.5">{employeeStats.workDays}</div>
                <p className="text-green-200 text-xs">Рабочих</p>
              </div>
            </div>

            {/* Отпуск */}
            <div className="relative group">
              <div className="absolute inset-0 bg-gradient-to-r from-blue-400 to-cyan-400 rounded-lg opacity-20 group-hover:opacity-30 transition-opacity blur-sm"></div>
              <div className="relative glass-card p-2 rounded-lg border border-blue-400/40 hover:border-blue-300/60 transition-all duration-200 text-center">
                <div className="relative w-6 h-6 mx-auto mb-1">
                  <svg className="w-6 h-6 transform -rotate-90" viewBox="0 0 36 36">
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="rgba(255,255,255,0.15)"
                      strokeWidth={3}
                    />
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="url(#gradient-blue-bright)"
                      strokeWidth={3}
                      strokeDasharray={`${(employeeStats.vacation / 5) * 100}, 100`}
                      strokeLinecap="round"
                    />
                  </svg>
                  <div className="absolute inset-0 flex items-center justify-center">
                    <Plane className="h-3 w-3 text-blue-300" />
                  </div>
                </div>
                <div className="text-white font-bold text-sm mb-0.5">{employeeStats.vacation}</div>
                <p className="text-blue-200 text-xs">Отпуск</p>
              </div>
            </div>

            {/* Больничный */}
            <div className="relative group">
              <div className="absolute inset-0 bg-gradient-to-r from-orange-400 to-red-400 rounded-lg opacity-20 group-hover:opacity-30 transition-opacity blur-sm"></div>
              <div className="relative glass-card p-2 rounded-lg border border-orange-400/40 hover:border-orange-300/60 transition-all duration-200 text-center">
                <div className="relative w-6 h-6 mx-auto mb-1">
                  <svg className="w-6 h-6 transform -rotate-90" viewBox="0 0 36 36">
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="rgba(255,255,255,0.15)"
                      strokeWidth={3}
                    />
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="url(#gradient-orange-bright)"
                      strokeWidth={3}
                      strokeDasharray={`${(employeeStats.sick / 3) * 100}, 100`}
                      strokeLinecap="round"
                    />
                  </svg>
                  <div className="absolute inset-0 flex items-center justify-center">
                    <Heart className="h-3 w-3 text-orange-300" />
                  </div>
                </div>
                <div className="text-white font-bold text-sm mb-0.5">{employeeStats.sick}</div>
                <p className="text-orange-200 text-xs">Больничный</p>
              </div>
            </div>

            {/* Переработка */}
            <div className="relative group">
              <div className="absolute inset-0 bg-gradient-to-r from-yellow-400 to-orange-400 rounded-lg opacity-20 group-hover:opacity-30 transition-opacity blur-sm"></div>
              <div className="relative glass-card p-2 rounded-lg border border-yellow-400/40 hover:border-yellow-300/60 transition-all duration-200 text-center">
                <div className="relative w-6 h-6 mx-auto mb-1">
                  <svg className="w-6 h-6 transform -rotate-90" viewBox="0 0 36 36">
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="rgba(255,255,255,0.15)"
                      strokeWidth={3}
                    />
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="url(#gradient-yellow-bright)"
                      strokeWidth={3}
                      strokeDasharray={`${(employeeStats.overtime / 20) * 100}, 100`}
                      strokeLinecap="round"
                    />
                  </svg>
                  <div className="absolute inset-0 flex items-center justify-center">
                    <Zap className="h-3 w-3 text-yellow-300" />
                  </div>
                </div>
                <div className="text-white font-bold text-sm mb-0.5">{employeeStats.overtime}ч</div>
                <p className="text-yellow-200 text-xs">Переработка</p>
              </div>
            </div>

            {/* KPI */}
            <div className="relative group">
              <div className="absolute inset-0 bg-gradient-to-r from-pink-400 to-purple-400 rounded-lg opacity-20 group-hover:opacity-30 transition-opacity blur-sm"></div>
              <div className="relative glass-card p-2 rounded-lg border border-pink-400/40 hover:border-pink-300/60 transition-all duration-200 text-center">
                <div className="relative w-6 h-6 mx-auto mb-1">
                  <svg className="w-6 h-6 transform -rotate-90" viewBox="0 0 36 36">
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="rgba(255,255,255,0.15)"
                      strokeWidth={3}
                    />
                    <path
                      d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
                      fill="none"
                      stroke="url(#gradient-pink-bright)"
                      strokeWidth={3}
                      strokeDasharray={`${employeeStats.kpi}, 100`}
                      strokeLinecap="round"
                    />
                  </svg>
                  <div className="absolute inset-0 flex items-center justify-center">
                    <Activity className="h-3 w-3 text-pink-300" />
                  </div>
                </div>
                <div className="text-white font-bold text-sm mb-0.5">{employeeStats.kpi}%</div>
                <p className="text-pink-200 text-xs">KPI</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Развернутая секция с табелем */}
      {isExpanded && (
        <div className="mt-2 pt-2 border-t border-white/10">
          {/* Дополнительная информация и управление */}
          <div className="mb-2 p-2 bg-white/5 rounded-md">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4 flex-wrap text-xs text-white/70">
                {/* Email */}
                <div className="flex items-center">
                  <Mail className="h-3 w-3 mr-1 flex-shrink-0" />
                  <span>{employee.email || 'Не указан'}</span>
                </div>

                {/* Зарплата */}
                <div className="flex items-center">
                  <Briefcase className="h-3 w-3 mr-1 flex-shrink-0" />
                  <span>{formatSalary(employee.salary)}</span>
                </div>

                {/* Дата приема */}
                <div className="flex items-center">
                  <Calendar className="h-3 w-3 mr-1 flex-shrink-0" />
                  <span>Принят: {formatDate(employee.hireDate)}</span>
                </div>

                {/* Дата рождения */}
                {employee.birthDate && (
                  <div className="flex items-center">
                    <Calendar className="h-3 w-3 mr-1 flex-shrink-0" />
                    <span>Родился: {formatDate(employee.birthDate)}</span>
                  </div>
                )}

                {/* Telegram */}
                {employee.telegram && (
                  <div className="flex items-center">
                    <MessageCircle className="h-3 w-3 mr-1 flex-shrink-0" />
                    <span>TG: {employee.telegram}</span>
                  </div>
                )}

                {/* WhatsApp */}
                {employee.whatsapp && (
                  <div className="flex items-center">
                    <Phone className="h-3 w-3 mr-1 flex-shrink-0" />
                    <span>WA: {employee.whatsapp}</span>
                  </div>
                )}
              </div>

              {/* Кнопки управления */}
              <div className="flex items-center gap-2 flex-shrink-0">
                <Button
                  size="sm"
                  variant="ghost"
                  className="text-white/60 hover:text-white hover:bg-white/10 h-8 w-8 p-0"
                  onClick={(e) => {
                    e.stopPropagation()
                    onEdit(employee)
                  }}
                >
                  <Edit className="h-4 w-4" />
                </Button>

                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button
                      size="sm"
                      variant="ghost"
                      className="text-red-400/60 hover:text-red-300 hover:bg-red-500/10 h-8 w-8 p-0"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <UserX className="h-4 w-4" />
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent className="glass-card border-white/10">
                    <AlertDialogHeader>
                      <AlertDialogTitle className="text-white">Уволить сотрудника?</AlertDialogTitle>
                      <AlertDialogDescription className="text-white/70">
                        Вы уверены, что хотите уволить сотрудника {employee.firstName} {employee.lastName}? Это действие
                        нельзя отменить.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel className="glass-secondary text-white hover:text-white">
                        Отмена
                      </AlertDialogCancel>
                      <AlertDialogAction
                        onClick={() => onDelete(employee.id)}
                        disabled={deletingEmployeeId === employee.id}
                        className="bg-red-600 hover:bg-red-700 text-white"
                      >
                        {deletingEmployeeId === employee.id ? 'Увольнение...' : 'Уволить'}
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              </div>
            </div>
          </div>

          {/* Табель работы и статистика - компактно */}
          <div className="space-y-3">
            <EmployeeCalendar
              employeeId={employee.id}
              employeeSchedules={employeeSchedules}
              currentYear={currentYear}
              currentMonth={currentMonth}
              onDayStatusChange={onDayStatusChange}
              onDayUpdate={onDayUpdate}
              employeeName={`${employee.firstName} ${employee.lastName}`}
            />
          </div>
        </div>
      )}
      {/* SVG градиенты для статистики */}
      <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>
    </Card>
  )
}
