import { useState, useEffect } from 'react'

import isEmpty from 'lodash/isEmpty'
import filter from 'lodash/filter'

import type { SportTypes } from 'config'

import type { TournamentsBySports } from 'requests/getSportTournaments'
import { getTournamentsBySports } from 'requests/getSportTournaments'

import { useRequest } from 'hooks'

export const useTournamentsBySports = (selectedSports: Array<SportTypes>) => {
  const [tournamentsBySports, setTournamentsBySports] = useState<TournamentsBySports>({})

  const {
    isFetching,
    request: fetchTournaments,
  } = useRequest(getTournamentsBySports)

  useEffect(() => {
    const missingTournaments = filter(selectedSports, (sport) => !tournamentsBySports[sport])
    if (!isEmpty(missingTournaments)) {
      fetchTournaments(missingTournaments).then((newTournaments) => {
        setTournamentsBySports({
          ...tournamentsBySports,
          ...newTournaments,
        })
      })
    }
  }, [selectedSports, tournamentsBySports, fetchTournaments])

  return {
    isFetching,
    tournamentsBySports,
  }
}
