import translate from "@insite/client-framework/Translate";
import { BillToModel, WebsiteSettingsModel } from "@insite/client-framework/Types/ApiModels";
import { useEffect, useState } from "react";

export type PaystandCard = {
    response: {
        data: PaystandCardData;
    };
};

export type BillingAddress = {
    object: string;
    id: string;
    street1: string;
    city: string;
    state: string;
    postalCode: string;
    country: string;
    status: string;
    created: Date;
    lastUpdated: Date;
};

export type Card = {
    object: string;
    id: string;
    nameOnCard: string;
    brand: string;
    last4: string;
    expirationMonth: string;
    expirationYear: string;
    fingerprint: string;
    payerId: string;
    billingAddress: BillingAddress;
    created: Date;
    lastUpdated: Date;
    status: string;
    funding: string;
};

export type Source = {
    nameOnCard: string;
    expirationMonth: string;
    expirationYear: string;
    brand: string;
    last4: string;
    fingerprint: string;
    payerId: string;
    funding: string;
    created: Date;
    lastUpdated: Date;
    status: string;
    id: string;
    billingAddress: BillingAddress;
    object: string;
};

export type Bank = {
    object: string;
    id: string;
    accountType: string;
    bankName: string;
    routingNumber: string;
    nameOnAccount: string;
    accountHolderType: string;
    currency: string;
    country: string;
    last4: string;
    isDefault: boolean;
    isApDefault: boolean;
    payerId: string;
    billingAddress: BillingAddress;
    dropped: boolean;
    verified: boolean;
    status: string;
    created: Date;
    lastUpdated: Date;
};

export type PaystandCardData = {
    cardId: string;
    payerId: string;
    bankId: string;
    id: string;
    card: Card;
    source: Source;
    bank: Bank;
};

export type PaystandIFrame = {
    setup: (billTo: BillToModel, readyCallback: () => void, paymentCallback: (data: PaystandCardData) => void) => void;
    getIsPaystandScriptLoaded: () => boolean;
    resetCheckout: (billTo: BillToModel) => void;
};

export type Paystand = {
    reboot: (config: any) => Paystand;
    showCheckout: () => void;
    readyImplemented: () => void;
    onReady: (callback: (data: any) => void) => void;
    onComplete: (callback: (data: PaystandCard) => void) => void;
    isReady: boolean;
    l: [];
};

declare let psCheckout: Paystand | null;

export const usePaystandFrame = (
    websiteSettings: WebsiteSettingsModel,
    paymentMethod: string,
    isCreditCard: boolean,
) => {
    const [isPaystandScriptLoaded, setIsPaystandScriptLoaded] = useState(false);
    useEffect(() => {
        if (websiteSettings.usePaystandDropIn && isCreditCard) {
            const script = document.createElement("script");
            script.src = !websiteSettings.paystandTestMode
                ? "https://checkout.paystand.com/v4/js/paystand.checkout.js"
                : "https://checkout.paystand.co/v4/js/paystand.checkout.js";
            script.async = true;
            script.setAttribute("id", "ps_checkout");
            script.setAttribute("ps-env", websiteSettings.paystandTestMode ? "sandbox" : "live");
            script.setAttribute("ps-publishableKey", websiteSettings.paystandPublishableKey);
            script.setAttribute("ps-containerId", "ps_container_id");
            script.setAttribute("ps-height", "700px");
            script.setAttribute("ps-width", "520px");
            script.setAttribute("ps-viewLogo", "hide");
            script.setAttribute("ps-viewSecure", "hide");
            script.setAttribute("ps-viewReceipt", "close");
            script.setAttribute("ps-mode", "modal");
            script.setAttribute("ps-hidePoweredBy", "true");
            script.setAttribute("ps-hideSupportInfo", "true");
            script.setAttribute("ps-checkoutType", "checkout_token");
            script.setAttribute("ps-fixedAmount", "true");
            script.setAttribute("ps-viewFunds", "card,ach,bank");
            script.setAttribute("ps-showField_payerEmail", "hide");
            script.setAttribute("ps-checkoutDescription", translate("Submit Payment Details"));
            script.onload = () => {
                setIsPaystandScriptLoaded(true);
            };

            document.body.appendChild(script);

            return () => {
                setIsPaystandScriptLoaded(false);
                document.body.removeChild(script);
            };
        }
    }, [paymentMethod]);

    const setup = (
        billTo: BillToModel,
        readyCallback: () => void,
        paymentCallback: (data: PaystandCardData) => void,
    ) => {
        if (psCheckout) {
            if (psCheckout?.isReady) {
                readyCallback?.();
                psCheckout.l = [];
                psCheckout?.onComplete(psData => {
                    const data = psData.response.data;
                    paymentCallback(data);
                });
                resetCheckout(billTo);
            }

            psCheckout.readyImplemented = () => {
                readyCallback?.();
                psCheckout?.onComplete(psData => {
                    const data = psData.response.data;
                    paymentCallback(data);
                });
                resetCheckout(billTo);
            };
        }
    };

    const resetCheckout = (billTo: BillToModel) => {
        psCheckout?.reboot({
            payerEmail: billTo.email,
            payerAddressCity: billTo.city,
            payerAddressPostal: billTo.postalCode,
            payerAddressStreet: billTo.address1,
            payerAddressState: billTo.state?.abbreviation,
        });
    };

    const getIsPaystandScriptLoaded = () => {
        return isPaystandScriptLoaded;
    };

    const paystandIFrame: PaystandIFrame = {
        setup,
        getIsPaystandScriptLoaded,
        resetCheckout,
    };

    return [paystandIFrame];
};
