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

import debounce from 'lodash/debounce'

import type { MatchInfo } from 'requests/getMatchInfo'

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

import { FULL_GAME_KEY } from 'features/MatchPage/helpers/buildPlaylists'
import { useDuration } from 'features/MultiSourcePlayer/hooks/useDuration'
import { useMatchPopupStore } from 'features/MatchPopup'

import { useMatchPlaylists } from './useMatchPlaylists'
import { useEvents } from './useEvents'

const MATCH_DATA_POLL_INTERVAL = 60000
const MATCH_PLAYLISTS_DELAY = 5000

export const useMatchData = (profile: MatchInfo) => {
  const { profileId: matchId, sportType } = usePageParams()
  const { chapters } = useMatchPopupStore()
  const [matchDuration, setMatchDuration] = useState(0)
  const {
    fetchMatchPlaylists,
    handlePlaylistClick,
    matchPlaylists,
    selectedPlaylist,
    setFullMatchPlaylistDuration,
    setSelectedPlaylist,
  } = useMatchPlaylists(profile)

  const { events, fetchMatchEvents } = useEvents()

  const fetchPlaylistsDebounced = useMemo(
    () => debounce(fetchMatchPlaylists, MATCH_PLAYLISTS_DELAY),
    [fetchMatchPlaylists],
  )
  const chaptersDuration = useDuration(chapters) / 1000
  const fullMatchDuration = matchDuration
  useEffect(() => {
    if (!profile) return
    fetchMatchPlaylists({
      fullMatchDuration,
      id: matchId,
      sportType,
    })
    fetchMatchEvents()
  }, [
    profile,
    fullMatchDuration,
    matchId,
    sportType,
    fetchMatchPlaylists,
    fetchMatchEvents,
  ])

  const intervalCallback = () => {
    fetchPlaylistsDebounced({
      fullMatchDuration,
      id: matchId,
      sportType,
    })
    fetchMatchEvents()
  }

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

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

  useEffect(() => {
    selectedPlaylist?.id === FULL_GAME_KEY && setMatchDuration(chaptersDuration)
    // eslint-disable-next-line
  }, [profile, chaptersDuration])

  useEffect(() => {
    setSelectedPlaylist(matchPlaylists.match[0])
    // eslint-disable-next-line
  }, [matchId])

  return {
    events,
    handlePlaylistClick,
    matchPlaylists,
    selectedPlaylist,
    setFullMatchPlaylistDuration,
    setSelectedPlaylist,
  }
}
