import { useEffect, useCallback } from 'react'

import uniq from 'lodash/uniq'
import map from 'lodash/map'

import { useToggle } from 'hooks'

import { useTournamentsBySports } from './useTournamentsBySports'
import { usePreferencesLoader } from './usePreferencesLoader'
import { useSelectedTournaments } from './useTournaments'
import { useSports } from './useSports'
import { useSearch } from './useSearch'

export const usePreferences = () => {
  const {
    close,
    isOpen,
    open,
  } = useToggle()

  const {
    fetchInitialSports,
    onSportSelect,
    selectedSports,
    setInitialSelectedSports,
    sports,
  } = useSports()

  const {
    isFetching: isFetchingTournaments,
    tournamentsBySports,
  } = useTournamentsBySports(selectedSports)

  const {
    clearQuery,
    onQueryChange,
    query,
    tournaments,
  } = useSearch(tournamentsBySports, selectedSports)

  const {
    allTournamentsSelected,
    isTournamentSelected,
    onSelectAllTournaments,
    onTournamentSelect,
    selectedTournaments,
    setInitialSelectedTournaments,
  } = useSelectedTournaments(selectedSports, tournaments)

  const {
    fetchInitialPreferences,
    isApplyButtonDisabled,
    isFetching: isFetchingPrefernces,
    isSaving,
    onApplyClick,
    userPreferences,
  } = usePreferencesLoader(selectedTournaments, close)

  const reset = useCallback(() => {
    if (!userPreferences) return

    const initialSelectedSports = uniq(map(
      userPreferences,
      ({ sport }) => sport,
    ))
    setInitialSelectedTournaments(userPreferences)
    setInitialSelectedSports(initialSelectedSports)
  }, [
    userPreferences,
    setInitialSelectedTournaments,
    setInitialSelectedSports,
  ])

  const openPopup = useCallback(() => {
    fetchInitialPreferences()
    fetchInitialSports()
    open()
  }, [fetchInitialPreferences, fetchInitialSports, open])

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

  useEffect(reset, [reset])

  return {
    allTournamentsSelected,
    clearQuery,
    closePopup,
    isApplyButtonDisabled,
    isFetching: isFetchingPrefernces || isSaving || isFetchingTournaments,
    isOpen,
    isTournamentSelected,
    onApplyClick,
    onQueryChange,
    onSelectAllTournaments,
    onSportSelect,
    onTournamentSelect,
    openPopup,
    query,
    selectedSports,
    sports,
    tournaments,
    userPreferences,
  }
}
