import useAppSelector from "@insite/client-framework/Common/Hooks/useAppSelector";
import { useEffect, useState } from "react";

declare let Stripe: ((publishableKey: string) => any) | null;

interface StripeRadarSessionResponse {
    radarSession?: {
        id: string;
        passive_captcha_site_key?: string;
    };
    error?: {
        message: string;
    };
}

export const useStripeSession = (onSessionUpdate: (sessionId: string) => void) => {
    const websiteSettings = useAppSelector(state => state.context.settings.settingsCollection.websiteSettings);
    const [isStripeRadarScriptLoaded, setIsStripeRadarScriptLoaded] = useState(false);
    const [stripeRadarSessionId, setStripeRadarSessionId] = useState(null as string | null);
    useEffect(() => {
        let radarScript = null;
        if (!websiteSettings.enabledSpreedlyStripeRadar || !websiteSettings.stripePublishableKey) {
            return;
        }
        radarScript = document.createElement("script");
        radarScript.src = "https://js.stripe.com/v3";
        radarScript.async = true;
        radarScript.onload = () => {
            setIsStripeRadarScriptLoaded(true);
            if (typeof Stripe === "undefined" || !Stripe) {
                return;
            }
            const stripe = Stripe(websiteSettings.stripePublishableKey);
            stripe.createRadarSession().then((response: StripeRadarSessionResponse) => {
                let radarSessionId: string | null;
                if (response.radarSession && response.radarSession.id) {
                    radarSessionId = response.radarSession.id;
                } else {
                    radarSessionId = null;
                }
                setStripeRadarSessionId(radarSessionId);
                if (radarSessionId) {
                    onSessionUpdate(radarSessionId);
                }
            });
        };

        document.body.appendChild(radarScript);

        return () => {
            document.body.removeChild(radarScript);
        };
    }, []);

    return {
        isStripeRadarScriptLoaded,
        stripeRadarSessionId,
    };
};
