import { useEffect, useState } from 'react'

import { useHeaderFiltersStore } from 'features/HeaderFilters'

import { SelectSport } from './components/SelectSport'
import { SelectSportPopup } from './components/SelectSportPopup'

const sports = {
  all_sports: 'all_sports',
  basketball: 'basketball',
  football: 'football_popup',
  handball: 'handball',
  hockey: 'hockey_popup',
  volleyball: 'volleyball',
}

export type SportsType = typeof sports

export const SportsFilter = () => {
  const {
    isShowTournament,
    selectedSport,
    setIsShowTournament,
    setSelectedLeague,
    setSelectedSport,
    sportIds,
  } = useHeaderFiltersStore()
  const [isOpen, setIsOpen] = useState(false)

  const onSportClick = (sport: string) => {
    if (!isShowTournament) return

    setSelectedSport([sport])
    setSelectedLeague(['all_competitions'])
    setIsShowTournament(true)
    setIsOpen(false)
  }

  const onModalOpen = () => {
    setIsOpen(true)
  }

  const onModalClose = () => {
    setIsOpen(false)
  }

  useEffect(() => {
    if (selectedSport.length === 0) setSelectedSport(['all_sports'])
  }, [selectedSport, setSelectedSport])

  return (
    <>
      <SelectSport
        onModalOpen={onModalOpen}
        open={isOpen}
        sport={selectedSport}
        sports={sports}
      />
      <SelectSportPopup
        onSportClick={onSportClick}
        isOpen={isOpen}
        onModalClose={onModalClose}
        selectedSport={selectedSport}
        sportIds={sportIds}
        sports={sports}
      />
    </>
  )
}
