import type { MouseEvent } from 'react'
import { 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, getWeeks } from '../helpers'

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

  const date = getDisplayDate({
    date: selectedDate,
    lang,
  })

  const onPreviousClick = () => {
    setSelectedDate(addDays(selectedDate, -7))
  }

  const onNextClick = () => {
    setSelectedDate(addDays(selectedDate, 7))
  }

  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,
  }
}
