import {
  MouseEvent,
  useEffect,
  useMemo,
} from 'react'

import addDays from 'date-fns/addDays'

import { useToggle } from 'hooks'

import { useLexicsStore } from 'features/LexicsStore'
import { useHeaderFiltersStore } from 'features/HeaderFilters'

import {
  getDisplayDate,
  getWeekName,
  getWeeks,
} from '../helpers'

export const useDateFilter = () => {
  const {
    selectedDate,
    setIsShowTournament,
    setSelectedDate,
    setSelectedFilters,
    setSelectedLeague,
    setSelectTournament,
  } = useHeaderFiltersStore()

  const { lang } = useLexicsStore()
  const {
    close,
    isOpen,
    open,
  } = useToggle()
  const week = useMemo(
    () => getWeeks(selectedDate, lang),
    [selectedDate, lang],
  )

  const date = getDisplayDate({
    date: selectedDate,
    lang,
  })
  const filters = localStorage.getItem('filters')
  const parseFilters = filters && JSON.parse(filters)
  const lastDate = parseFilters?.selectedDate
  const weekName = getWeekName(selectedDate, 'en')
  useEffect(() => {
    if (lastDate === selectedDate.getDate()
        && parseFilters
        && parseFilters.selectedLeague[0] !== 'all_competitions') {
      setIsShowTournament(false)
      setSelectedLeague(parseFilters.selectedLeague)
      setSelectTournament(parseFilters.selectTournament)
    } else {
      setIsShowTournament(true)
      setSelectedFilters([])
      setSelectedLeague(['all_competitions'])
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedDate])

  const onPreviousClick = () => {
    const numberAddDays = weekName === 'Mon' ? -1 : -7
    setSelectedDate(addDays(selectedDate, numberAddDays))
  }

  const onNextClick = () => {
    const numberAddDays = weekName === 'Sun' ? 1 : 7
    setSelectedDate(addDays(selectedDate, numberAddDays))
  }

  const onDateChange = (newDate: Date | null) => {
    if (newDate) {
      setSelectedDate(newDate)
      close()
    }
  }

  const openDatePicker = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation()
    open()
  }

  return {
    close,
    date,
    isOpen,
    onDateChange,
    onNextClick,
    onPreviousClick,
    onWeekDayClick: setSelectedDate,
    openDatePicker,
    selectedDate,
    week,
  }
}
