import {
  useCallback,
  useEffect,
  useState,
} from 'react'

import { format } from 'date-fns'

import { useAuthStore } from 'features/AuthStore'
import { useHeaderFiltersStore } from 'features/HeaderFilters'

import { getHomeMatches } from 'requests/getMatches'
import { getAgreements, setAgreements } from 'requests/getAgreements'

/**
 * возвращает смещение в минутах относительно UTC
 *
 * Date.getTimezoneOffset() для UTC+3 возвращает -180
 * но api ожидает 180 поэтому инвертируем смещение
 */
const getTimezoneOffset = (date: Date) => {
  const offset = date.getTimezoneOffset()
  if (offset === 0) return offset
  return -(offset)
}

const getDate = (date: Date) => format(date, 'yyyy-MM-dd')

export const useHomePage = () => {
  const { user } = useAuthStore()
  const { queryParams, selectedDate } = useHeaderFiltersStore()
  const [isOpenDownload, setIsOpenDownload] = useState(false)
  const [isShowConfirmPopup, setIsShowConfirmPopup] = useState(false)

  const handleCloseConfirmPopup = useCallback(async () => {
    await setAgreements(user?.profile?.email || '')
    setIsShowConfirmPopup(false)
  }, [setIsShowConfirmPopup, user])

  useEffect(() => {
    (async () => {
      const agreement = await getAgreements(user?.profile?.email || '')
      if (!agreement?.is_agreement_privacy_policy && !agreement?.is_agreement_terms_conditions) {
        setIsShowConfirmPopup(true)
      }
    })()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  useEffect(() => {
    const dateLastOpenSmartBanner = localStorage.getItem('dateLastOpenSmartBanner')
    if (!dateLastOpenSmartBanner
      || Date.parse(JSON.parse(dateLastOpenSmartBanner)) < Date.parse(new Date().toISOString())
    ) {
      setIsOpenDownload(true)
    }
  }, [])

  const fetchMatches = useCallback((limit: number, offset: number) => getHomeMatches(
    {
      date: getDate(selectedDate),
      limit,
      offset,
      queryParams,
      timezoneOffset: getTimezoneOffset(selectedDate),

    },
  ), [selectedDate, queryParams])

  return {
    fetchMatches,
    handleCloseConfirmPopup,
    isOpenDownload,
    isShowConfirmPopup,
    setIsOpenDownload,
  }
}
