// =============================================================================
// 🧑‍💼 EMPLOYEE LIST BLOCK V2
// =============================================================================
// Модульный блок списка сотрудников с пагинацией

'use client'

import { Edit, Trash2, Calendar, Phone, Mail, Users } from 'lucide-react'
import React, { useCallback } from 'react'

import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'

import type { EmployeeV2, PaginationInfo } from '../types'

interface EmployeeListBlockProps {
  employees: EmployeeV2[]
  pagination: PaginationInfo | null
  loading?: boolean
  onEdit?: (employee: EmployeeV2) => void
  onDelete?: (id: string) => void
  onViewSchedule?: (employee: EmployeeV2) => void
  onPageChange?: (page: number) => void
}

export const EmployeeListBlock = React.memo(function EmployeeListBlock({
  employees,
  pagination,
  loading = false,
  onEdit,
  onDelete,
  onViewSchedule,
  onPageChange,
}: EmployeeListBlockProps) {
  
  // =============================================================================
  // ОБРАБОТЧИКИ
  // =============================================================================

  const handleEdit = useCallback((employee: EmployeeV2) => {
    onEdit?.(employee)
  }, [onEdit])

  const handleDelete = useCallback((id: string) => {
    if (confirm('Вы уверены что хотите удалить сотрудника?')) {
      onDelete?.(id)
    }
  }, [onDelete])

  const handleViewSchedule = useCallback((employee: EmployeeV2) => {
    onViewSchedule?.(employee)
  }, [onViewSchedule])

  const handlePageChange = useCallback((page: number) => {
    onPageChange?.(page)
  }, [onPageChange])

  // =============================================================================
  // RENDER HELPERS
  // =============================================================================

  const getStatusBadge = (status: string) => {
    const variants = {
      ACTIVE: 'bg-green-500/20 text-green-300 border-green-500/30',
      VACATION: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
      SICK: 'bg-orange-500/20 text-orange-300 border-orange-500/30',
      FIRED: 'bg-red-500/20 text-red-300 border-red-500/30',
    }

    const labels = {
      ACTIVE: 'Активен',
      VACATION: 'В отпуске',
      SICK: 'На больничном',
      FIRED: 'Уволен',
    }

    return (
      <span className={`px-2 py-1 rounded-full text-xs border ${variants[status as keyof typeof variants] || variants.ACTIVE}`}>
        {labels[status as keyof typeof labels] || status}
      </span>
    )
  }

  const formatSalary = (salary?: number) => {
    if (!salary) return '-'
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
      maximumFractionDigits: 0,
    }).format(salary)
  }

  const formatDate = (date: Date) => {
    return new Date(date).toLocaleDateString('ru-RU')
  }

  // =============================================================================
  // RENDER
  // =============================================================================

  if (loading && employees.length === 0) {
    return (
      <Card className="glass-card p-6">
        <div className="flex items-center justify-center h-32">
          <div className="text-white/60">Загружаем сотрудников...</div>
        </div>
      </Card>
    )
  }

  if (employees.length === 0) {
    return (
      <Card className="glass-card p-6">
        <div className="text-center py-8">
          <Users className="h-12 w-12 text-white/30 mx-auto mb-4" />
          <h3 className="text-white font-medium mb-2">Сотрудники не найдены</h3>
          <p className="text-white/60">Попробуйте изменить параметры поиска или добавьте первого сотрудника</p>
        </div>
      </Card>
    )
  }

  return (
    <Card className="glass-card p-6">
      
      {/* Заголовок списка */}
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-white font-medium text-lg">
          Сотрудники {pagination && `(${pagination.total})`}
        </h3>
        {loading && (
          <div className="text-white/60 text-sm">Обновление...</div>
        )}
      </div>

      {/* Список сотрудников */}
      <div className="space-y-3">
        {employees.map((employee) => (
          <div
            key={employee.id}
            className="flex items-center justify-between p-4 rounded-lg bg-white/5 hover:bg-white/10 transition-all"
          >
            
            {/* Основная информация */}
            <div className="flex items-center space-x-4">
              {/* Аватар */}
              <div className="w-10 h-10 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 flex items-center justify-center text-white font-medium">
                {employee.personalInfo.firstName[0]}{employee.personalInfo.lastName[0]}
              </div>

              {/* Данные */}
              <div>
                <div className="text-white font-medium">
                  {employee.personalInfo.fullName}
                </div>
                <div className="text-white/60 text-sm">
                  {employee.workInfo.position}
                  {employee.workInfo.department && ` • ${employee.workInfo.department}`}
                </div>
                <div className="flex items-center space-x-4 mt-1">
                  <div className="flex items-center space-x-1 text-white/50 text-xs">
                    <Phone className="h-3 w-3" />
                    <span>{employee.contactInfo.phone}</span>
                  </div>
                  {employee.contactInfo.email && (
                    <div className="flex items-center space-x-1 text-white/50 text-xs">
                      <Mail className="h-3 w-3" />
                      <span>{employee.contactInfo.email}</span>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Статус и действия */}
            <div className="flex items-center space-x-4">
              
              {/* Статус */}
              {getStatusBadge(employee.workInfo.status)}

              {/* Зарплата */}
              {employee.workInfo.salary && (
                <div className="text-white/60 text-sm">
                  {formatSalary(employee.workInfo.salary)}
                </div>
              )}

              {/* Дата найма */}
              <div className="text-white/50 text-xs">
                с {formatDate(employee.workInfo.hireDate)}
              </div>

              {/* Действия */}
              <div className="flex items-center space-x-2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleViewSchedule(employee)}
                  className="text-white/60 hover:text-white hover:bg-white/10"
                >
                  <Calendar className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleEdit(employee)}
                  className="text-white/60 hover:text-white hover:bg-white/10"
                >
                  <Edit className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleDelete(employee.id)}
                  className="text-red-400 hover:text-red-300 hover:bg-red-500/10"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Пагинация */}
      {pagination && pagination.totalPages > 1 && (
        <div className="flex items-center justify-center mt-6 space-x-2">
          <Button
            variant="outline"
            size="sm"
            disabled={pagination.page <= 1}
            onClick={() => handlePageChange(pagination.page - 1)}
            className="text-white border-white/20 hover:bg-white/10"
          >
            Назад
          </Button>

          <div className="flex items-center space-x-1">
            {Array.from({ length: Math.min(pagination.totalPages, 5) }, (_, i) => {
              const pageNum = pagination.page <= 3 
                ? i + 1 
                : pagination.page + i - 2
                
              if (pageNum > pagination.totalPages) return null

              return (
                <Button
                  key={pageNum}
                  variant={pageNum === pagination.page ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => handlePageChange(pageNum)}
                  className={
                    pageNum === pagination.page
                      ? 'bg-purple-600 text-white'
                      : 'text-white border-white/20 hover:bg-white/10'
                  }
                >
                  {pageNum}
                </Button>
              )
            })}
          </div>

          <Button
            variant="outline"
            size="sm"
            disabled={pagination.page >= pagination.totalPages}
            onClick={() => handlePageChange(pagination.page + 1)}
            className="text-white border-white/20 hover:bg-white/10"
          >
            Вперед
          </Button>
        </div>
      )}
    </Card>
  )
})