import type { FormEvent } from 'react'
import { useEffect, useState } from 'react'

import isEmpty from 'lodash/isEmpty'

import { ProfileTypes } from 'config'

import { useToggle } from 'hooks'

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

import type { NormalizedSearchResults } from '../helpers'

export type Profiles = keyof NormalizedSearchResults

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

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

  const [selectedTab, setSelectedTab] = useState<Profiles>(ProfileTypes.TOURNAMENTS)

  useEffect(() => {
    if (isEmpty(searchItems[selectedTab])) {
      const getNextNonEmptySelected = () => {
        if (!isEmpty(searchItems[ProfileTypes.TOURNAMENTS])) {
          return ProfileTypes.TOURNAMENTS
        }
        if (!isEmpty(searchItems[ProfileTypes.TEAMS])) {
          return ProfileTypes.TEAMS
        }
        return ProfileTypes.PLAYERS
      }
      setSelectedTab(getNextNonEmptySelected())
    }
  }, [searchItems, selectedTab])

  useEffect(() => {
    const allEmpty = (
      isEmpty(searchItems[ProfileTypes.PLAYERS])
      && isEmpty(searchItems[ProfileTypes.TEAMS])
      && isEmpty(searchItems[ProfileTypes.TOURNAMENTS])
    )

    if (allEmpty) {
      close()
    } else {
      open()
    }
    return () => {
      setSelectedTab(ProfileTypes.TOURNAMENTS)
    }
  }, [searchItems, close, open])

  const closePopup = () => {
    close()
    reset()
  }

  const onSubmit = (e: FormEvent<HTMLFormElement>) => e.preventDefault()

  return {
    clearQuery,
    close: closePopup,
    isFetching,
    isOpen,
    onChange: onQueryChange,
    onSubmit,
    onTabClick: setSelectedTab,
    query,
    searchItems,
    selectedTab: selectedTab as Profiles,
    showResults: isOpen,
  }
}
