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 { filterKeys } from '../config'
import { isValidDate } from '../helpers/isValidDate'

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<any>()
  const isTodaySelected = isToday(selectedDate)

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

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

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

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

  return store
}
