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,
  getAgreements,
  setAgreements,
  getCountryCode,
} from 'requests'

import { setLocalStorageItem } from 'helpers'

import { COUNTRY } from 'config'

import { isSportFilterShownAtom } from './Atoms/HomePageAtoms'
import { useAds } from '../../components/Ads/hooks'

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

  const { ads } = useAds()

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

  const countryCode = async () => {
    const { country_code } = await getCountryCode()
    country_code && setLocalStorageItem(COUNTRY, country_code)

    return country_code
  }

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

    countryCode()
  }, [])

  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, userInfo?.email],
  )

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

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