import { useState, useEffect } from 'react'
import { getBaseDomain } from '@junwon/config'
import { useVisa } from '../providers/VisaProvider'
import { YStack, Button, Paragraph } from '@junwon/aesthetics'
import { Link } from '../components/Link'
import { VisaCard } from '../components/VisaCard'

export function ManageMembership() {
  const { isSignedIn, loading, getStripePortalLink } = useVisa()
  const [portalLink, setPortalLink] = useState<string>('')
  const [error, setError] = useState<string>('')
  const baseDomain = getBaseDomain('visa-web')

  useEffect(() => {
    async function fetchPortalLink() {
      if (!isSignedIn || !baseDomain) return

      setError('')

      try {
        const link = await getStripePortalLink(baseDomain)
        setPortalLink(link)
      } catch (err) {
        setError('Stripe server is experiencing issues. Please try again later or contact support.')
        console.log('Failed to get Stripe portal link:', err)
      }
    }

    fetchPortalLink()
  }, [baseDomain, isSignedIn, getStripePortalLink])

  return (
    <YStack
      f={1}
      pt="$6"
      pb="$12"
      gap="$3"
    >
      <VisaCard />
      <Paragraph>{loading ? 'Loading...' : ''}</Paragraph>
      <Paragraph col="$red10">{error ? error : ''}</Paragraph>
      {isSignedIn && (
        <Link href={portalLink}>
          <Button w="100%">Open Stripe Portal</Button>
        </Link>
      )}
    </YStack>
  )
}
