// =============================================================================
// 🧑‍💼 EMPLOYEE FILTERS BLOCK V2
// =============================================================================
// Блок фильтров и поиска сотрудников

'use client'

import { Search, Filter, X, Calendar } from 'lucide-react'
import React, { useCallback } from 'react'

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

import type { EmployeesFilterInput, EmployeeStatus, EmployeeSortField } from '../types'

interface EmployeeFiltersBlockProps {
  filters: EmployeesFilterInput
  updateFilter: <K extends keyof EmployeesFilterInput>(
    key: K, 
    value: EmployeesFilterInput[K]
  ) => void
  resetFilters: () => void
  hasActiveFilters: boolean
  loading?: boolean
}

export const EmployeeFiltersBlock = React.memo(function EmployeeFiltersBlock({
  filters,
  updateFilter,
  resetFilters,
  hasActiveFilters,
  loading = false,
}: EmployeeFiltersBlockProps) {

  // =============================================================================
  // ОБРАБОТЧИКИ
  // =============================================================================

  const handleSearchChange = useCallback((value: string) => {
    updateFilter('search', value || undefined)
  }, [updateFilter])

  const handleStatusChange = useCallback((value: string) => {
    if (value === 'all') {
      updateFilter('status', undefined)
    } else {
      updateFilter('status', [value as EmployeeStatus])
    }
  }, [updateFilter])

  const handleDepartmentChange = useCallback((value: string) => {
    updateFilter('department', value || undefined)
  }, [updateFilter])

  const handleSortChange = useCallback((value: string) => {
    const [sortBy, sortOrder] = value.split(':') as [EmployeeSortField, 'asc' | 'desc']
    updateFilter('sortBy', sortBy)
    updateFilter('sortOrder', sortOrder)
  }, [updateFilter])

  const handleDateFromChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    updateFilter('dateFrom', value ? new Date(value) : undefined)
  }, [updateFilter])

  const handleDateToChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value  
    updateFilter('dateTo', value ? new Date(value) : undefined)
  }, [updateFilter])

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

  return (
    <Card className="glass-card p-4">
      <div className="space-y-4">
        
        {/* Основной поиск */}
        <div className="flex items-center space-x-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-white/40 h-4 w-4" />
            <Input
              placeholder="Поиск по имени, должности, телефону..."
              value={filters.search || ''}
              onChange={(e) => handleSearchChange(e.target.value)}
              className="pl-10 bg-white/5 border-white/20 text-white placeholder:text-white/40"
              disabled={loading}
            />
          </div>

          {hasActiveFilters && (
            <Button
              variant="outline"
              size="sm"
              onClick={resetFilters}
              className="text-white border-white/20 hover:bg-white/10"
            >
              <X className="h-4 w-4 mr-1" />
              Сбросить
            </Button>
          )}
        </div>

        {/* Дополнительные фильтры */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          
          {/* Статус */}
          <div>
            <label className="text-white/60 text-xs uppercase font-medium mb-2 block">
              Статус
            </label>
            <Select
              value={filters.status?.[0] || 'all'}
              onValueChange={handleStatusChange}
              disabled={loading}
            >
              <SelectTrigger className="bg-white/5 border-white/20 text-white">
                <SelectValue placeholder="Все статусы" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Все статусы</SelectItem>
                <SelectItem value="ACTIVE">Активные</SelectItem>
                <SelectItem value="VACATION">В отпуске</SelectItem>
                <SelectItem value="SICK">На больничном</SelectItem>
                <SelectItem value="FIRED">Уволенные</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Отдел */}
          <div>
            <label className="text-white/60 text-xs uppercase font-medium mb-2 block">
              Отдел
            </label>
            <Input
              placeholder="Отдел..."
              value={filters.department || ''}
              onChange={(e) => handleDepartmentChange(e.target.value)}
              className="bg-white/5 border-white/20 text-white placeholder:text-white/40"
              disabled={loading}
            />
          </div>

          {/* Сортировка */}
          <div>
            <label className="text-white/60 text-xs uppercase font-medium mb-2 block">
              Сортировка
            </label>
            <Select
              value={`${filters.sortBy}:${filters.sortOrder}`}
              onValueChange={handleSortChange}
              disabled={loading}
            >
              <SelectTrigger className="bg-white/5 border-white/20 text-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="NAME:asc">Имя (А-Я)</SelectItem>
                <SelectItem value="NAME:desc">Имя (Я-А)</SelectItem>
                <SelectItem value="POSITION:asc">Должность (А-Я)</SelectItem>
                <SelectItem value="HIRE_DATE:desc">Дата найма (новые)</SelectItem>
                <SelectItem value="HIRE_DATE:asc">Дата найма (старые)</SelectItem>
                <SelectItem value="CREATED_AT:desc">Создано (новые)</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Размер страницы */}
          <div>
            <label className="text-white/60 text-xs uppercase font-medium mb-2 block">
              На странице
            </label>
            <Select
              value={filters.limit?.toString() || '20'}
              onValueChange={(value) => updateFilter('limit', parseInt(value))}
              disabled={loading}
            >
              <SelectTrigger className="bg-white/5 border-white/20 text-white">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="10">10</SelectItem>
                <SelectItem value="20">20</SelectItem>
                <SelectItem value="50">50</SelectItem>
                <SelectItem value="100">100</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* Фильтры по датам найма */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="text-white/60 text-xs uppercase font-medium mb-2 block flex items-center">
              <Calendar className="h-3 w-3 mr-1" />
              Принят с
            </label>
            <Input
              type="date"
              value={filters.dateFrom ? new Date(filters.dateFrom).toISOString().split('T')[0] : ''}
              onChange={handleDateFromChange}
              className="bg-white/5 border-white/20 text-white"
              disabled={loading}
            />
          </div>

          <div>
            <label className="text-white/60 text-xs uppercase font-medium mb-2 block flex items-center">
              <Calendar className="h-3 w-3 mr-1" />
              Принят до
            </label>
            <Input
              type="date"
              value={filters.dateTo ? new Date(filters.dateTo).toISOString().split('T')[0] : ''}
              onChange={handleDateToChange}
              className="bg-white/5 border-white/20 text-white"
              disabled={loading}
            />
          </div>
        </div>
      </div>
    </Card>
  )
})