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

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

import { usePageParams } from 'hooks/usePageParams'
import { openSubscribePopup } from '../../helpers'
import { MATCH_CONFIG } from '../BuyMatchPopup/store/hooks/useSubscriptions'
import { useBuyMatchPopupStore } from '../BuyMatchPopup'

export const useTeamPage = () => {
  const [teamProfile, setTeamProfile] = useState<TeamInfo>(null)
  const { profileId: teamId, sportType } = usePageParams()
  const { open: openBuyMatchPopup } = useBuyMatchPopupStore()

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

  useEffect(() => {
    openSubscribePopup({
      matchConfig: MATCH_CONFIG,
      openBuyMatchPopup,
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  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,
    headerImage: teamProfile?.header_image,
    profile,
    sportType,
    teamId,
  }
}
