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

import trim from 'lodash/trim'
import size from 'lodash/size'

import { ProfileTypes } from 'config'

import { MIN_CHARACTERS_LENGTH } from 'features/Search/config'
import type { NormalizedSearchResults } from 'features/Search/helpers'

import { useSearchRequest } from './useSearchRequest'

const initialState = {
  [ProfileTypes.PLAYERS]: [],
  [ProfileTypes.TEAMS]: [],
  [ProfileTypes.TOURNAMENTS]: [],
}

export const useExtendedSearch = () => {
  const [searchItems, setSearchItems] = useState<NormalizedSearchResults>(initialState)

  const [query, setQuery] = useState('')

  const {
    cancelSearch,
    isFetching,
    search,
  } = useSearchRequest(setSearchItems)

  const onQueryChange = useCallback(
    ({ target: { value } }: ChangeEvent<HTMLInputElement>) => {
      setQuery(value)
    },
    [],
  )

  const clearQuery = () => setQuery('')

  const trimmedQuery = trim(query)
  useEffect(() => {
    cancelSearch()
    if (size(trimmedQuery) >= MIN_CHARACTERS_LENGTH) {
      search(trimmedQuery)
    }
  }, [
    trimmedQuery,
    search,
    cancelSearch,
  ])

  const reset = useCallback(() => {
    setSearchItems(initialState)
    setQuery('')
  }, [])

  return {
    clearQuery,
    isFetching,
    onQueryChange,
    query,
    reset,
    searchItems,
  }
}
