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

import type { TournamentInfo } from 'requests'
import { getTournamentInfo, getTournamentMatches } from 'requests'

import { usePageParams } from 'hooks/usePageParams'

import { useName } from 'features/Name'

export const useTournamentPage = () => {
  const [tournamentProfile, setTournamentProfile] = useState<TournamentInfo>(null)
  const { profileId: tournamentId, sportType } = usePageParams()
  const country = useName(tournamentProfile?.country || {})

  useEffect(() => {
    getTournamentInfo(sportType, tournamentId)
      .then(setTournamentProfile)
  },
  [
    sportType,
    tournamentId,
  ])

  const fetchMatches = useCallback(
    (limit: number, offset: number) => getTournamentMatches({
      limit,
      offset,
      sportType,
      tournamentId,
    }),
    [
      tournamentId,
      sportType,
    ],
  )

  const profile = tournamentProfile && {
    additionalInfo: tournamentProfile.country,
    name_eng: tournamentProfile.name_eng,
    name_rus: tournamentProfile.name_rus,
  }

  return {
    fetchMatches,
    headerImage: tournamentProfile?.header_image,
    infoItems: [country],
    profile,
    tournamentId,
  }
}
