// =============================================================================
// 🧑‍💼 EMPLOYEE FILTERS HOOK V2
// =============================================================================
// Хук для управления фильтрами и поиском сотрудников

'use client'

import { useState, useCallback, useMemo } from 'react'

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

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

const DEFAULT_FILTERS: EmployeesFilterInput = {
  page: 1,
  limit: 20,
  sortBy: 'NAME' as EmployeeSortField,
  sortOrder: 'ASC',
}

export function useEmployeeFilters(
  initialFilters: EmployeesFilterInput = {},
): UseEmployeeFiltersReturn {
  
  const [filters, setFilters] = useState<EmployeesFilterInput>({
    ...DEFAULT_FILTERS,
    ...initialFilters,
  })

  // Обновление конкретного фильтра
  const updateFilter = useCallback(<K extends keyof EmployeesFilterInput>(
    key: K,
    value: EmployeesFilterInput[K],
  ) => {
    setFilters(prev => ({
      ...prev,
      [key]: value,
      // При изменении фильтров сбрасываем на первую страницу
      page: key === 'page' ? value as number : 1,
    }))
  }, [])

  // Сброс фильтров
  const resetFilters = useCallback(() => {
    setFilters(DEFAULT_FILTERS)
  }, [])

  // Проверка наличия активных фильтров
  const hasActiveFilters = useMemo(() => {
    return !!(
      filters.status?.length ||
      filters.department ||
      filters.search ||
      filters.dateFrom ||
      filters.dateTo
    )
  }, [filters])

  // Хелперы для частых операций
  const setSearch = useCallback((search: string) => {
    updateFilter('search', search)
  }, [updateFilter])

  const setStatus = useCallback((status: EmployeeStatus[]) => {
    updateFilter('status', status)
  }, [updateFilter])

  const setDepartment = useCallback((department: string) => {
    updateFilter('department', department)
  }, [updateFilter])

  const setPage = useCallback((page: number) => {
    updateFilter('page', page)
  }, [updateFilter])

  const setSort = useCallback((sortBy: EmployeeSortField, sortOrder: 'ASC' | 'DESC' = 'ASC') => {
    setFilters(prev => ({
      ...prev,
      sortBy,
      sortOrder,
      page: 1, // сброс на первую страницу при сортировке
    }))
  }, [])

  return {
    filters,
    setFilters,
    updateFilter,
    resetFilters,
    hasActiveFilters,
    
    // Удобные хелперы
    setSearch,
    setStatus,
    setDepartment,
    setPage,
    setSort,
  }
}