import { useEffect, useState } from 'react'

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

import { useLexicsStore } from 'features/LexicsStore'

import { useSportNameParam, usePageId } from 'hooks'

type Name = 'name_rus' | 'name_eng'

export const useMatchProfileCard = () => {
  const [matchProfile, setMatchProfile] = useState<MatchInfo>(null)
  const { sportType } = useSportNameParam()
  const pageId = usePageId()
  const { suffix } = useLexicsStore()

  const addNames = (profile: MatchInfo, suffixArg: string) => (
    profile
      ? ({
        ...profile,
        team1: {
          ...profile.team1,
          name: profile.team1[`name_${suffixArg}` as Name],
        },
        team2: {
          ...profile.team2,
          name: profile.team2[`name_${suffixArg}` as Name],
        },
        tournament: {
          ...profile.tournament,
          name: profile.tournament[`name_${suffixArg}` as Name],
        },
      })
      : null
  )

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

  return {
    matchProfile: addNames(matchProfile, suffix),
  }
}
