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

import { format } from 'date-fns'

import { useSetRecoilState } from 'recoil'

import { client } from 'config/clients'
import { ClientNames } from 'config/clients/types'

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

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

import { isSportFilterShownAtom } from './Atoms/HomePageAtoms'

/**
 * возвращает смещение в минутах относительно 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, userInfo } = useAuthStore()
  const { selectedDate } = useHeaderFiltersStore()
  const [isOpenDownload, setIsOpenDownload] = useState(false)
  const [isShowConfirmPopup, setIsShowConfirmPopup] = useState(false)
  const setIsSportFilterShown = useSetRecoilState(isSportFilterShownAtom)

  const handleCloseConfirmPopup = useCallback(async () => {
    await setAgreements(`${userInfo?.email}` || '')
    setIsShowConfirmPopup(false)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [setIsShowConfirmPopup, userInfo])

  useEffect(() => {
    if (userInfo?.email) {
      (async () => {
        const agreement = await getAgreements(`${userInfo?.email}` || '')
        if (!agreement?.is_agreement_privacy_policy && !agreement?.is_agreement_terms_conditions) {
          setIsShowConfirmPopup(true)
        }
      })()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userInfo?.email])

  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,
      timezoneOffset: getTimezoneOffset(selectedDate),
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [selectedDate, user],
  )

  useEffect(() => {
    if (client.name === ClientNames.Facr) {
      setIsSportFilterShown(false)
    }
  }, [setIsSportFilterShown])

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