import { useMemo } from 'react'

import { useQuery } from 'react-query'

import { useRecoilState } from 'recoil'

import { isMobileDevice, querieKeys } from 'config'

import { getAds } from 'requests'

import { isMatchPage } from 'helpers/isMatchPage'
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'

type Props = {
  matchId?: number,
  sportType?: number,
  tournamentId?: number,
}

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

  useQuery({
    enabled: isMatchPage() ? (!!user && !!tournamentId) : !!user,
    queryFn: async () => {
      const adsList = await getAds({
        client_type: isMobileDevice ? DeviceType.MOBILE : DeviceType.WEB,
        language: lang,
        type_id: isMatchPage() ? PageType.MATCH : PageType.HOME,
        ...isMatchPage() && {
          matches: [{
            match_id: matchId,
            sport_id: sportType,
          }],
          tournaments: [{
            sport_id: sportType,
            tournament_id: tournamentId,
          }],
        },
      })
      adsList && setAds(adsList)
      return adsList
    },
    queryKey: [querieKeys.ads, matchId],
    staleTime: useMemo(() => Math.max(calcMaxAdDurationAds(ads), 60 * 1000), [ads]),
  })

  return {
    ads,
  }
}
