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

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

import { usePageParams } from 'hooks/usePageParams'

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

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])

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

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

  return {
    events,
    profile,
  }
}
