import type { ReactNode } from 'react'
import { Fragment, useEffect } from 'react'

import type { MatchInfo } from 'requests/getMatchInfo'

import { usePageParams } from 'hooks/usePageParams'

import { useBuyMatchPopupStore } from 'features/BuyMatchPopup'

import { prepareMatchProfile } from '../../helpers/prepareMatchProfile'

type Props = {
  children: ReactNode,
  matchProfile: MatchInfo,
}

export const SubscriptionGuard = ({ children, matchProfile }: Props) => {
  const { open: openBuyMatchPopup } = useBuyMatchPopupStore()
  const { profileId: matchId, sportType } = usePageParams()

  useEffect(() => {
    if (matchProfile && !matchProfile.sub) {
      const profile = prepareMatchProfile({
        matchId,
        profile: matchProfile,
        sportType,
      })
      openBuyMatchPopup(profile)
    }
  }, [
    matchId,
    openBuyMatchPopup,
    matchProfile,
    sportType,
  ])

  return (
    <Fragment>
      {matchProfile?.sub ? children : null}
    </Fragment>
  )
}
