import {
  useMemo,
  useEffect,
  useCallback,
} from 'react'
import { useLocation } from 'react-router-dom'
import { isToday } from 'date-fns'

import { useQueryParamStore } from 'hooks'

import { filterKeys } from '../config'
import { serializeDate } from '../helpers/dateSerializers'
import { isValidDate } from '../helpers/isValidDate'

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

  const isTodaySelected = isToday(selectedDate)

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

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

  const store = useMemo(() => ({
    isTodaySelected,
    selectedDate,
    setSelectedDate,
  }), [
    isTodaySelected,
    selectedDate,
    setSelectedDate,
  ])

  return store
}
