import { useEffect, useMemo } from 'react'

import debounce from 'lodash/debounce'

import { usePageParams } from 'hooks/usePageParams'
import { useInterval } from 'hooks/useInterval'

import { useMatchPopupStore } from 'features/MatchPopup'

import { useEvents } from './useEvents'

const MATCH_DATA_POLL_INTERVAL = 60000
const MATCH_PLAYLISTS_DELAY = 5000

export const useMatchData = (live: boolean = false) => {
  const { profileId: matchId, sportType } = usePageParams()
  const { fetchMatchPlaylists, matchPlaylists } = useMatchPopupStore()
  const { events, fetchMatchEvents } = useEvents()

  const fetchPlaylistsDebounced = useMemo(
    () => debounce(fetchMatchPlaylists, MATCH_PLAYLISTS_DELAY),
    [fetchMatchPlaylists],
  )

  useEffect(() => {
    fetchMatchPlaylists({
      id: matchId,
      sportType,
      withFullMatchDuration: !live,
    })
    fetchMatchEvents()
  }, [
    live,
    matchId,
    sportType,
    fetchMatchPlaylists,
    fetchMatchEvents,
  ])

  const intervalCallback = () => {
    fetchPlaylistsDebounced({
      id: matchId,
      sportType,
      withFullMatchDuration: !live,
    })
    fetchMatchEvents()
  }

  const { start, stop } = useInterval({
    callback: intervalCallback,
    intervalDuration: MATCH_DATA_POLL_INTERVAL,
    startImmediate: false,
  })

  useEffect(() => {
    if (live) {
      start()
    } else {
      stop()
    }
  }, [live, start, stop])

  return { events, matchPlaylists }
}
