/**
 * Hook для фильтрации и поиска контрагентов
 * Обрабатывает локальные фильтры и поиск через API
 */

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

// Простая реализация debounce для hook
function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])

  return debouncedValue
}

import type {
  UseCounterpartyFiltersReturn,
  OrganizationType,
} from '../types'

interface UseCounterpartyFiltersProps {
  onSearch?: (query: string, type?: OrganizationType) => void
}

export function useCounterpartyFilters({
  onSearch,
}: UseCounterpartyFiltersProps): UseCounterpartyFiltersReturn {
  // Состояние фильтров для поиска
  const [searchQuery, setSearchQuery] = useState('')
  const [typeFilter, setTypeFilter] = useState<OrganizationType>('all')

  // Debounced поиск
  const debouncedSearch = useDebounce(searchQuery, 500)

  // Автоматический поиск при изменении запроса или типа
  useEffect(() => {
    if (onSearch) {
      onSearch(debouncedSearch, typeFilter === 'all' ? undefined : typeFilter)
    }
  }, [debouncedSearch, typeFilter, onSearch])

  // Обработчики изменений
  const handleSearchChange = useCallback((query: string) => {
    setSearchQuery(query)
  }, [])

  const handleTypeFilterChange = useCallback((type: OrganizationType) => {
    setTypeFilter(type)
  }, [])

  return {
    searchQuery,
    typeFilter,
    debouncedSearch,
    handleSearchChange,
    handleTypeFilterChange,
  }
}