import type { FormEvent } from 'react'
import { useCallback, useEffect } from 'react'
import { useHistory } from 'react-router-dom'

import { PAGES } from 'config'

import { useToggle } from 'hooks'

import { useExtendedSearchStore } from 'features/ExtendedSearchPage/store'

export const useSearch = () => {
  const history = useHistory()
  const {
    isFetching,
    onQueryChange,
    query,
    reset,
    searchItems,
  } = useExtendedSearchStore()

  const {
    close,
    isOpen,
    open,
  } = useToggle()

  const onSubmit = useCallback((e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    history.push(PAGES.extendedSearch)
  }, [history])

  useEffect(() => {
    reset()
  }, [reset, isOpen])

  return {
    close,
    isFetching,
    onChange: onQueryChange,
    onFocus: open,
    onSubmit,
    query,
    searchItems,
    showResults: isOpen,
  }
}
