import { useCallback, useState } from 'react'

import includes from 'lodash/includes'
import without from 'lodash/without'
import isEmpty from 'lodash/isEmpty'

import type { SportTypes } from 'config'
import type { SportList } from 'requests/getSportList'
import { getSportList } from 'requests/getSportList'

export const useSports = () => {
  const [sports, setSports] = useState<SportList>([])
  const [selectedSports, setSelectedSports] = useState<Array<SportTypes>>([])

  const fetchInitialSports = useCallback(() => {
    if (isEmpty(sports)) {
      getSportList().then(setSports)
    }
  }, [sports])

  const onSportSelect = (sport: SportTypes) => {
    const newSports = includes(selectedSports, sport)
      ? without(selectedSports, sport)
      : [sport, ...selectedSports]
    setSelectedSports(newSports)
  }

  return {
    fetchInitialSports,
    onSportSelect,
    selectedSports,
    setInitialSelectedSports: setSelectedSports,
    sports,
  }
}
