import type { Dispatch, SetStateAction } from 'react'
import {
  useEffect,
  useState,
  useMemo,
} from 'react'

import throttle from 'lodash/throttle'
import isUndefined from 'lodash/isUndefined'

import type { MatchInfo } from 'requests'
import { getTeamsStats, TeamStatItem } from 'requests'

import { usePageParams } from 'hooks/usePageParams'

import type { PlaylistOption } from 'features/MatchPage/types'
import { StatsType } from 'features/MatchSidePlaylists/components/TabStats/config'
import { FULL_GAME_KEY } from 'features/MatchPage/helpers/buildPlaylists'
import { getHalfTime } from 'features/MatchPage/helpers/getHalfTime'

const REQUEST_DELAY = 3000
const STATS_POLL_INTERVAL = 30000

type UseTeamsStatsArgs = {
  matchProfile: MatchInfo,
  playingProgress: number,
  selectedPlaylist?: PlaylistOption,
  setIsTeamsStatsFetching: Dispatch<SetStateAction<boolean>>,
  statsType: StatsType,
}

export const useTeamsStats = ({
  matchProfile,
  playingProgress,
  selectedPlaylist,
  setIsTeamsStatsFetching,
  statsType,
}: UseTeamsStatsArgs) => {
  const [teamsStats, setTeamsStats] = useState<{
    [teamId: string]: Array<TeamStatItem>,
  }>({})

  const { profileId: matchId, sportName } = usePageParams()

  const isCurrentStats = statsType === StatsType.CURRENT_STATS

  const fetchTeamsStats = useMemo(() => throttle(async (second?: number) => {
    if (!sportName || selectedPlaylist?.id !== FULL_GAME_KEY || !matchProfile?.video_bounds) return

    try {
      const data = await getTeamsStats({
        matchId,
        sportName,
        ...(!isUndefined(second) && getHalfTime(matchProfile.video_bounds, second)),
      })

      setTeamsStats(data)
      setIsTeamsStatsFetching(false)

    // eslint-disable-next-line no-empty
    } catch (e) {}
  }, REQUEST_DELAY), [
    matchProfile?.video_bounds,
    selectedPlaylist?.id,
    matchId,
    setIsTeamsStatsFetching,
    sportName,
  ])

  useEffect(() => {
    let interval: NodeJS.Timeout

    if (!isCurrentStats) {
      fetchTeamsStats()
    }

    if (matchProfile?.live && !isCurrentStats) {
      interval = setInterval(() => {
        fetchTeamsStats()
      }, STATS_POLL_INTERVAL)
    }

    return () => clearInterval(interval)
  }, [fetchTeamsStats, matchProfile?.live, isCurrentStats])

  useEffect(() => {
    if (isCurrentStats) {
      fetchTeamsStats(playingProgress)
    }
  }, [fetchTeamsStats, playingProgress, isCurrentStats])

  return {
    statsType,
    teamsStats,
  }
}
