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

import { usePageParams } from 'hooks/usePageParams'

import { useBuyMatchPopupStore } from 'features/BuyMatchPopup'
import { useMatchPageStore } from 'features/MatchPage/store'

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

type Props = {
  children: ReactNode,
}

export const SubscriptionGuard = ({ children }: Props) => {
  const { profile: matchProfile } = useMatchPageStore()
  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>
  )
}
