import { useMemo } from 'react'

import { useQuery } from 'react-query'

import { useRecoilState } from 'recoil'

import { isMobileDevice, querieKeys } from 'config'

import { getAds } from 'requests'

import { useLang } from 'features/LexicsStore/hooks/useLang'

import { useAuthStore } from 'features/AuthStore'

import {
  DeviceType,
  PageType,
} from './types'
import { calcMaxAdDurationAds } from './helpers/calcMaxDurationAds'
import { adsStore } from '../../pages/HighlightsPage/storeHighlightsAtoms'

export const useAds = () => {
  const [ads, setAds] = useRecoilState(adsStore)
  const { lang } = useLang()
  const { user } = useAuthStore()

  useQuery({
    queryFn: async () => {
      if (user) {
        const adsList = await getAds({
          client_type: isMobileDevice ? DeviceType.MOBILE : DeviceType.WEB,
          language: lang,
          type_id: PageType.HOME,
        })
        adsList && setAds(adsList)
        return adsList
      }
      return {}
    },
    queryKey: querieKeys.ads,
    staleTime: useMemo(() => Math.max(calcMaxAdDurationAds(ads), 60 * 1000), [ads]),
  })

  return {
    ads,
  }
}
