import type { ChangeEvent, MouseEvent } from 'react'
import {
  useState,
  useEffect,
  useMemo,
} from 'react'

import debounce from 'lodash/debounce'

import type { SportTypes } from 'config'
import type { Tournaments, TournamentsBySports } from 'requests/getSportTournaments'

import { useLexicsStore } from 'features/LexicsStore'

import { search } from '../helpers'

type SearchArgs = Parameters<typeof search>[0]

export const useSearch = (
  tournamentsBySports: TournamentsBySports,
  selectedSports: Array<SportTypes>,
) => {
  const { suffix } = useLexicsStore()

  const [query, setQuery] = useState('')
  const [tournaments, setTournaments] = useState<Tournaments>([])

  const onQueryChange = (e: ChangeEvent<HTMLInputElement>) => {
    setQuery(e.target.value)
  }

  const clearQuery = (e: MouseEvent) => {
    e.stopPropagation()
    setQuery('')
  }

  const debouncedSearch = useMemo(() => debounce((args: SearchArgs) => {
    search(args).then(setTournaments)
  }, 300), [])

  useEffect(() => {
    debouncedSearch({
      query,
      selectedSports,
      suffix,
      tournamentsBySports,
    })
  }, [
    selectedSports,
    query,
    tournamentsBySports,
    suffix,
    debouncedSearch,
  ])

  return {
    clearQuery,
    onQueryChange,
    query,
    tournaments,
  }
}
