import {
  useMemo,
  useEffect,
  useCallback,
  useState,
} from 'react'
import { useLocation } from 'react-router-dom'

import { isToday } from 'date-fns'

import type { TournamentType } from 'requests/getMatches/types'

import { useQueryParamStore } from 'hooks'

import { getSportLexic } from 'helpers'

import { SPORT_NAMES, SportTypes } from 'config'

import { filterKeys } from '../config'
import { isValidDate } from '../helpers/isValidDate'
import type { Match } from '../../../Matches'

export const useFilters = () => {
  const { search } = useLocation()
  const [selectedDate, setSelectedDate] = useQueryParamStore({
    clearOnUnmount: true,
    defaultValue: new Date(),
    key: filterKeys.DATE,
    validator: isValidDate,
  })

  const [selectedSport, setSelectedSport] = useState(['all_sports'])
  const [selectedLeague, setSelectedLeague] = useState<Array<string | number>>(['all_competitions'])
  const [selectedFilters, setSelectedFilters] = useState<Array<string>>([])
  const [isShowTournament, setIsShowTournament] = useState(true)
  const [selectTournament, setSelectTournament] = useState<TournamentType>()
  const [sportIds, setSportIds] = useState<Array<number>>([])
  const isTodaySelected = isToday(selectedDate)

  const compareSport = useCallback((match: Match, sportNames: Array<string>) => {
    if (sportNames[0] === 'all_sports') {
      return true
    }
    const sport = getSportLexic(match.sportType)
    return (sportNames.indexOf(sport) >= 0 || sportNames.indexOf(`${sport}_popup`) >= 0)
  }, [])

  const updateSportIds = useCallback((matches:Array<Match>) => {
    const sportTypeIds = new Set<number>([])
    matches.forEach((match) => {
      sportTypeIds.add(match.sportType)
    })
    setSportIds(Array.from(sportTypeIds))

    if (!Array.from(sportTypeIds)?.some((id: SportTypes) => SPORT_NAMES[id] === selectedSport[0])
    ) {
      setSelectedSport(['all_sports'])
    }
  }, [selectedSport])

  const resetFilters = useCallback(() => {
    setIsShowTournament(true)
    setSelectedFilters([])
    setSelectedLeague(['all_competitions'])
  }, [])

  const updateDate = useCallback(() => {
    setSelectedDate(new Date())
  }, [setSelectedDate])

  useEffect(() => {
    localStorage.setItem('filters', JSON.stringify({
      selectTournament,
      selectedDate: selectedDate.getDate(),
      selectedLeague,
    }))
    // eslint-disable-next-line
  }, [selectedLeague])

  useEffect(() => {
    if (!search) {
      updateDate()
    }
  }, [
    isTodaySelected,
    updateDate,
    search,
  ])

  const store = useMemo(() => ({
    compareSport,
    isShowTournament,
    isTodaySelected,
    resetFilters,
    selectTournament,
    selectedDate,
    selectedFilters,
    selectedLeague,
    selectedSport,
    setIsShowTournament,
    setSelectTournament,
    setSelectedDate,
    setSelectedFilters,
    setSelectedLeague,
    setSelectedSport,
    setSportIds,
    sportIds,
    updateDate,
    updateSportIds,
  }), [
    compareSport,
    isShowTournament,
    isTodaySelected,
    resetFilters,
    selectedDate,
    selectedFilters,
    selectedLeague,
    selectedSport,
    selectTournament,
    setSelectTournament,
    setIsShowTournament,
    setSelectedDate,
    setSelectedFilters,
    setSelectedLeague,
    setSelectedSport,
    setSportIds,
    sportIds,
    updateDate,
    updateSportIds,
  ])

  return store
}
