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 { isSubscribePopup } from 'helpers'

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

type Props = {
  children: ReactNode,
}

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

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

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