import React, { useEffect } from "react";
import { PaymentRequestTokenEvent } from "@stripe/stripe-js";
import { useStripe, PaymentRequestButtonElement } from '@stripe/react-stripe-js';

import { useStyles } from "./styles";

type AppleGooglePayProps = {
    price: number,
    currency: string,
    isPaymentRequestShowed?: boolean,
    setPaymentRequest: (arg: any) => any,
    setStripeResult: (arg: any) => any,
    setGpayLoaded: (arg: boolean) => void,
    setApayLoaded: (arg: boolean) => void,
    stripeResult: any,
    onSubmit: any,
    paymentRequest: any,
}

export const AppleGooglePay = ({
    price,
    currency,
    isPaymentRequestShowed,
    setPaymentRequest,
    setStripeResult,
    onSubmit,
    paymentRequest,
    stripeResult,
    setGpayLoaded,
    setApayLoaded
}: AppleGooglePayProps) => {
    const stripe = useStripe();
    const { appleGooglePay } = useStyles();

    const submitPayment = (result: Record<string, boolean>) => (e: PaymentRequestTokenEvent) => {
        if (result?.applePay) {
            onSubmit({ event: e, price, type: 'applePay' });
        }

        if (result?.googlePay) {
            onSubmit({ event: e, price, type: 'googlePay' });
        }
    };

    const handleReady = () => {
        const { googlePay, applePay } = stripeResult || {};

        if(googlePay) {
            setGpayLoaded(true);
        }

        if(applePay) {
            setApayLoaded(true);
        }
    }

    useEffect(() => {
        if(price && stripe && currency) {
            const pr = stripe?.paymentRequest({
                country: 'GB',
                currency: currency?.toLowerCase(),
                total: {
                    label: 'Hint',
                    amount: price,
                },
                requestPayerName: true,
                requestPayerEmail: true,
            });
            pr.canMakePayment().then((result) => {
                if (result) {
                    setStripeResult(result);
                    pr.on('token', submitPayment(result));
                    setPaymentRequest(pr);
                } else {
                    setGpayLoaded(true);
                    setApayLoaded(true);
                }
            })
        }

    }, [stripe, price, currency]);

    if (!isPaymentRequestShowed) return null;

    return (
        <PaymentRequestButtonElement
            onReady={handleReady}
            options={{
                paymentRequest,
                style: {
                    paymentRequestButton: {
                        height: '48px'
                    }
                }
            }}
            className={appleGooglePay}
        />
    )
}