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

import { usePageParams } from 'hooks/usePageParams'

import type { PlayerProfile } from 'requests/getPlayerInfo'
import { getPlayerInfo, getPlayerMatches } from 'requests'

import { openSubscribePopup } from 'helpers'

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

export const usePlayerPage = () => {
  const [playerProfile, setPlayerProfile] = useState<PlayerProfile>(null)
  const { profileId: playerId, sportType } = usePageParams()
  const { open: openBuyMatchPopup } = useBuyMatchPopupStore()

  const {
    firstname_eng = '',
    firstname_rus = '',
    lastname_eng = '',
    lastname_rus = '',
  } = playerProfile || {}

  const profile = playerProfile && {
    additionalInfo: {
      ...playerProfile.club_team,
      id: playerProfile.country.id,
    },
    name_eng: `${firstname_eng} ${lastname_eng}`,
    name_rus: `${firstname_rus} ${lastname_rus}`,
  }

  useEffect(() => {
    getPlayerInfo(playerId, sportType).then(setPlayerProfile)
  }, [playerId, sportType])

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

  const fetchMatches = useCallback(
    (limit: number, offset: number) => getPlayerMatches({
      limit,
      offset,
      playerId,
      sportType,
      sub_only: true,
    }),
    [
      playerId,
      sportType,
    ],
  )

  return {
    fetchMatches,
    playerProfile,
    profile,
    teamId: playerProfile?.club_team?.id,
  }
}
