import React, {useEffect, useState} from 'react';
import { Elements } from '@stripe/react-stripe-js';

import { PrimaryButton } from "../buttons/primary_button";
import { ModalWindow } from "../modal_window";
import { CheckoutForm } from "./checkout_form";
import { AppleGooglePay } from "./apple_google_pay";
import { AmazonButton } from "./amazon_button";
import { PayPal } from "./pay_pal";
import { Divider } from "./divider";
import { LoaderBox } from "../loader_box";
import { InfoBlock } from "../info_block";

import creditCard from '../../assets/paywall/credit_card.svg';
import { useStyles } from "./styles";

export type PaywallProps = {
    accessPaymentsKeys: {
        checkoutPayKey: string,
        braintreeAuthorization?: string,
        stripePromise?: any,
        amazonSellerId: string,
        amazonClientId: string
    },
    stripeProp: {
        price: number,
        currency: string
    }
    countryCode: string,
    onSubmit: any,
    isApplePayActive: boolean,
    isGooglePayActive: boolean,
    isPaypalActive: boolean,
    isAmazonActive: boolean,
    env: string,
    onAmazonButtonClicked: () => void,
    formText?: any,
    onComponentReady?: () => void,
    cardError: string,
    error: string,
    loading?: boolean,
    forceReadyComponentTime?: number,
    isModalCheckoutOpened?: boolean,
    modalCheckoutWindowTriggered?: (arg: boolean) => void
}

export const Paywall = ({
    onAmazonButtonClicked,
    accessPaymentsKeys,
    countryCode,
    onSubmit,
    stripeProp,
    isApplePayActive,
    isGooglePayActive,
    isPaypalActive,
    isAmazonActive,
    env,
    formText,
    onComponentReady = () => {},
    cardError,
    error,
    loading,
    forceReadyComponentTime = 4000,
    isModalCheckoutOpened = false,
    modalCheckoutWindowTriggered = () => {}
}: PaywallProps) => {
    const {
        button, buttonContent, cardIcon,
        hiddenWindow, wrapper, active,
        errorBlock
    } = useStyles();
    const [open, setOpen] = useState(false)
    const [paymentRequest, setPaymentRequest] = useState<PaymentRequest | null>(null);
    const [stripeResult, setStripeResult] = useState<Record<string, boolean> | null>(null);
    const [gPayLoaded, setGpayLoaded] = useState(!isGooglePayActive);
    const [aPayLoaded, setApayLoaded] = useState(!isApplePayActive);
    const [pPalLoaded, setPayPalLoaded] = useState(!isPaypalActive);

    const toggleModal = () => {
        setOpen(!open)
        modalCheckoutWindowTriggered(!open)
    }

    const {
        checkoutPayKey, stripePromise, braintreeAuthorization,
        amazonClientId, amazonSellerId
    } = accessPaymentsKeys;
    const isAppleGooglePayShowed =  isApplePayActive || isGooglePayActive;
    const isPaymentRequestShowed = !!(stripeResult?.googlePay && paymentRequest)
        || !!(stripeResult?.applePay && paymentRequest);

    const isDividerShowed = (isAppleGooglePayShowed && isPaymentRequestShowed) || isPaypalActive || isAmazonActive;

    useEffect(() => {
        const isComponentReady = gPayLoaded && aPayLoaded && pPalLoaded;

        if(isComponentReady && onComponentReady) {
            onComponentReady()
        }
    }, [gPayLoaded, aPayLoaded, pPalLoaded]);

    useEffect(() => {
        setTimeout(() => {
            setApayLoaded(true);
            setGpayLoaded(true);
            setPayPalLoaded(true);
        }, forceReadyComponentTime);
    }, [])

    useEffect(() => setOpen(isModalCheckoutOpened), [isModalCheckoutOpened])

    const isComponentReady = gPayLoaded && aPayLoaded && pPalLoaded;

    const wrapperClass = `${wrapper} ${isComponentReady ? active: ''}`;

    if(loading) return <LoaderBox />;

    return (
        <>
            {!isComponentReady && <LoaderBox />}
            {error && isComponentReady && (
                <InfoBlock
                    className={errorBlock}
                    text={error}
                    variant="error"
                />
            )}
            <div className={wrapperClass}>
                {isAppleGooglePayShowed && stripePromise && (
                    <Elements stripe={stripePromise}>
                        <AppleGooglePay
                            setGpayLoaded={setGpayLoaded}
                            setApayLoaded={setApayLoaded}
                            paymentRequest={paymentRequest}
                            onSubmit={onSubmit}
                            setPaymentRequest={setPaymentRequest}
                            setStripeResult={setStripeResult}
                            isPaymentRequestShowed={isPaymentRequestShowed}
                            {...stripeProp}
                        />
                    </Elements>
                )}
                {isPaypalActive && (
                    <PayPal
                        setPayPalLoaded={setPayPalLoaded}
                        braintreeAuthorization={braintreeAuthorization}
                        onSubmit={onSubmit}
                    />
                )}
                {isAmazonActive && (
                    <AmazonButton
                        onAuth={onAmazonButtonClicked}
                        clientId={amazonClientId}
                        sellerId={amazonSellerId}
                        env={env}
                    />
                )}
                {isDividerShowed && <Divider />}
                <PrimaryButton
                    onClick={toggleModal}
                    className={button}
                    //@ts-ignore
                    label={(
                        <div className={buttonContent}>
                            <img className={cardIcon} src={creditCard} alt=""/>
                            Credit / Debit Card
                        </div>
                    )}
                />
                <ModalWindow
                    open
                    rootClassName={!open || !isComponentReady ? hiddenWindow : ''}
                >
                    <CheckoutForm
                        error={cardError}
                        formText={formText}
                        handleClose={toggleModal}
                        onSubmit={onSubmit}
                        countryCode={countryCode}
                        publicKey={checkoutPayKey}
                    />
                </ModalWindow>
            </div>
        </>
    )
}