import React, { useEffect } from "react";

import { PayPalProps } from "../";
import { useStyles } from "./styles";

export const Content = ({ onSubmit, braintreeAuthorization, setPayPalLoaded }: PayPalProps) => {
    const { payPal } = useStyles();

    useEffect(() => {
        //@ts-ignore
        window.braintree?.client.create({
            authorization: braintreeAuthorization,
        }, function (clientErr: any, clientInstance: any) {

            if (clientErr) {
                console.error('Error creating client:', clientErr);
                return;
            }

            //@ts-ignore
            window.braintree?.paypalCheckout.create({
                client: clientInstance,
            }, function (_:any, paypalCheckoutInstance: any) {
                paypalCheckoutInstance.loadPayPalSDK({
                    currency: 'USD',
                    intent: 'capture',
                    vault: true,
                }, function () {
                    //@ts-ignore
                    window.paypal?.Buttons({
                        style: {
                            layout:  'vertical',
                            height: 48,
                        },
                        //@ts-ignore
                        fundingSource: window.paypal.FUNDING.PAYPAL,
                        createBillingAgreement: function () {
                            return paypalCheckoutInstance.createPayment({
                                flow: 'vault', // Required
                                enableShippingAddress: true,
                            });
                        },
                        onApprove: function (data: any) {
                            return paypalCheckoutInstance.tokenizePayment(data, (_: any, payload: any) =>
                                onSubmit({ type: 'payPal', ...payload })
                            );
                        },
                        onCancel: function (data: any) {
                            //@ts-ignore
                            console.log('PayPal payment canceled', JSON.stringify(data, 0, 2));
                        },
                        onError: function (err: any) {
                            console.error('PayPal error', err);
                        }
                    }).render('#paypal-button')
                        .then(() => {
                            console.log('paypal ready')
                            setPayPalLoaded(true)
                        });
                });
            });
        });
    }, []);

    return <div className={payPal} id="paypal-button" />
}
