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

import type { MatchInfo } from 'requests'
import { getMatchInfo } from 'requests'

import { usePageParams } from 'hooks/usePageParams'

import { parseDate } from 'helpers/parseDate'

import type { Playlists } from '../types'
import { useMatchData } from './useMatchData'
import { useTournamentData } from './useTournamentData'

const addScoresFromPlaylists = (
  profile: MatchInfo,
  playlists: Playlists,
): MatchInfo => (
  profile
    ? {
      ...profile,
      team1: {
        ...profile?.team1,
        score: playlists.score1,
      },
      team2: {
        ...profile?.team2,
        score: playlists.score2,
      },
    }
    : null
)

export const useMatchProfile = () => {
  const [matchProfile, setMatchProfile] = useState<MatchInfo>(null)
  const { profileId: matchId, sportType } = usePageParams()

  useEffect(() => {
    getMatchInfo(sportType, matchId).then(setMatchProfile)
  }, [sportType, matchId])

  useEffect(() => {
    let getIntervalMatch: ReturnType<typeof setInterval>
    if (matchProfile?.live && !matchProfile.youtube_link) {
      getIntervalMatch = setInterval(
        () => getMatchInfo(sportType, matchId).then(setMatchProfile), 1000 * 60 * 3,
      )
    }
    return () => clearInterval(getIntervalMatch)
  }, [matchProfile, sportType, matchId])

  const { events, matchPlaylists } = useMatchData(matchProfile?.live)

  const profile = useMemo(
    () => addScoresFromPlaylists(matchProfile, matchPlaylists),
    [matchProfile, matchPlaylists],
  )

  const { tournamentData } = useTournamentData(matchProfile?.tournament.id ?? null)

  const isStarted = useMemo(() => (
    profile?.date
      ? parseDate(profile.date) < new Date()
      : true
  ), [profile?.date])

  return {
    events,
    isStarted,
    profile,
    tournamentData,
  }
}
