import { useUpdatePushToken } from '@/pages/profile/hooks/useProfileData'
import { FC, useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'

declare global {
    interface Window {
        NAJVA: {
            getUserToken: () => Promise<string>
            najvaUserSubscribed: (najvaUserToken: string) => void
        }
    }
}

const NajvaToken: FC = () => {
    const { pathname } = useLocation()
    const [isNajvaToken, setIsNajvaToken] = useState(false)
    const [retryCount, setRetryCount] = useState(0)
    const updatePushToken = useUpdatePushToken()

    const handleNajvaToken = async () => {
        try {

            if (!window.NAJVA) {
                return false
            }

            const userToken = await window.NAJVA.getUserToken()

            if (userToken) {
                await updatePushToken.mutateAsync({
                    pushToken: userToken,
                })
                setIsNajvaToken(true)
                return true
            } else {
                return false
            }
        } catch {
            return false
        }
    }

    const tryGetToken = async () => {
        const success = await handleNajvaToken()

        if (!success && retryCount < 5) {
            setTimeout(() => {
                setRetryCount(prev => prev + 1)
            }, (retryCount + 1) * 1000)
        }
    }

    useEffect(() => {
        if (!isNajvaToken) {
            tryGetToken()
        }
    }, [pathname, isNajvaToken, retryCount])

    return null
}

export default NajvaToken