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,
    onSubmit: any,
    paymentRequest: any,
}

export const AppleGooglePay = ({
    price,
    currency,
    isPaymentRequestShowed,
    setPaymentRequest,
    setStripeResult,
    onSubmit,
    paymentRequest,
    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 = () => {
        console.log('stripe component ready')
        setApayLoaded(true);
        setGpayLoaded(true);
    }

    useEffect(() => {
        console.log('before start stripe init')
        if(price && stripe && currency) {
            console.log('start stripe init')
            const pr = stripe?.paymentRequest({
                country: 'GB',
                currency: currency?.toLowerCase(),
                total: {
                    label: 'Hint',
                    amount: price,
                },
                requestPayerName: true,
                requestPayerEmail: true,
            });
            pr.canMakePayment().then((result) => {
                console.log('start stripe promise')
                if (result) {
                    console.log('stripe result exists')
                    setStripeResult(result);
                    pr.on('token', submitPayment(result));
                    setPaymentRequest(pr);
                } else {
                    console.log('stripe result not exists')
                    handleReady();
                }
            })
        }

    }, [stripe, price, currency]);

    console.log('isPaymentRequestShowed', isPaymentRequestShowed);

    if (!isPaymentRequestShowed) return null;

    console.log('rendered');

    return (
        <PaymentRequestButtonElement
            onReady={() => {
                console.log('apple google pay ready')
                handleReady();
            }}
            options={{
                paymentRequest,
                style: {
                    paymentRequestButton: {
                        height: '48px'
                    }
                }
            }}
            className={appleGooglePay}
        />
    )
}