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

import throttle from 'lodash/throttle'

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

import { usePageParams } from 'hooks/usePageParams'

import { StatsType } from 'features/MatchSidePlaylists/components/TabStats/config'

const REQUEST_DELAY = 3000
const STATS_POLL_INTERVAL = 30000

type UseTeamsStatsArgs = {
  matchProfile: MatchInfo,
  playingProgress: number,
  statsType: StatsType,
}

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

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

  const progressSec = Math.floor(playingProgress / 1000)

  const isCurrentStats = statsType === StatsType.CURRENT_STATS

  const fetchTeamsStats = useMemo(() => throttle((second?: number) => {
    if (!sportName) return

    getTeamsStats({
      matchId,
      second,
      sportName,
    }).then(setTeamsStats)
  }, REQUEST_DELAY), [matchId, sportName])

  useEffect(() => {
    let timer: ReturnType<typeof setInterval>

    if (!isCurrentStats) {
      fetchTeamsStats()
    }

    if (matchProfile?.live) {
      timer = setInterval(() => {
        if (isCurrentStats) return

        fetchTeamsStats()
      }, STATS_POLL_INTERVAL)
    }

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

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

  return {
    statsType,
    teamsStats,
  }
}
