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

import type { TeamInfo } from 'requests'
import { getTeamInfo, getTeamMatches } from 'requests'

import { useSportNameParam, usePageId } from 'hooks'

export const useTeamPage = () => {
  const [teamProfile, setTeamProfile] = useState<TeamInfo>(null)
  const { sportType } = useSportNameParam()
  const teamId = usePageId()

  useEffect(() => {
    getTeamInfo(sportType, teamId)
      .then(setTeamProfile)
  },
  [
    sportType,
    teamId,
  ])

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

  const profile = teamProfile && {
    additionalInfo: {
      id: teamProfile.country.id,
      name_eng: teamProfile.tournament?.name_eng,
      name_rus: teamProfile.tournament?.name_rus,
      tournamentId: teamProfile.tournament?.id,
    },
    name_eng: teamProfile.name_eng,
    name_rus: teamProfile.name_rus,
  }

  return {
    fetchMatches,
    profile,
    sportType,
    teamId,
  }
}
