import React, { useEffect, useState, useCallback } from 'react';
import { Box, Typography } from '@material-ui/core';
import { PaymentTenderTypeEnum } from '../../../../enums/paymentTenderTypeEnum';
import { PaymentVendorFactoryEnum } from '../../../../enums/paymentVendorFactoryEnum';
import { useTranslation } from 'react-i18next';
import { LayoutUnit } from '../../../../layout/LayoutUnit';
import { apiMutate } from '../../../useAxiosMutate';
import { useUser } from '../../../auth/useUser';
import { CircularProgress } from '../../../../UI/loading/CircularProgress';
import { v4 as uuid } from 'uuid';
import { ConfigService } from '../../../../configService';
;
export const PaymentusForm = ({ paymentMethod = PaymentTenderTypeEnum.CreditCard, onStatusChange = null, paymentDetails = null, baseUrl = "https://secure4.paymentus.com/xotp/pm/sgc2", attributes = null, paymentData = null }) => {
    const methodURL = (paymentMethod === PaymentTenderTypeEnum.CreditCard) ? 'creditcard' : 'echeck';
    const [src, setSrc] = useState(`${baseUrl}`);
    const [response, setResponse] = useState({});
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const user = useUser();
    const [paymentTokenCreditCardIDGuid] = useState(uuid());
    const [paymentTokenIDGuid] = useState(uuid());
    const { t } = useTranslation();
    /**
     * API call to get the Paymentus Token
     */
    const getPaymentusToken = useCallback(async (payload) => {
        if (!payload) {
            return null;
        }
        return apiMutate(ConfigService.pgV1ApiUrl, `ProcessHostedPaymentPagePayment/authToken/${methodURL}`, {
            method: 'POST',
            data: payload
        }, {});
    }, []);
    /**
     * API post the generated Token
     */
    const postPaymentusToken = useCallback(async (payload) => {
        if (!payload) {
            return null;
        }
        const PostURL = (paymentMethod === PaymentTenderTypeEnum.CreditCard) ?
            'PaymentTokenCreditCard/ByPass' : 'PaymentTokenECheck/CreateByPass';
        return apiMutate(ConfigService.pgV1ApiUrl, `${PostURL}`, {
            method: 'POST',
            data: payload,
        }, {});
    }, []);
    /**
     * handleFiservResponse
     *
     * @param {*} response
     */
    const handlePaymentusResponse = useCallback((response) => {
        const isError = response === null || response === void 0 ? void 0 : response.error;
        const paymentFormResponse = {
            isValid: !isError,
            payload: response,
            message: response === null || response === void 0 ? void 0 : response.Token,
            errorCode: response === null || response === void 0 ? void 0 : response.error,
            errorMessage: response === null || response === void 0 ? void 0 : response.error,
            selectedHostedPayment: PaymentVendorFactoryEnum.Paymentus
        };
        onStatusChange === null || onStatusChange === void 0 ? void 0 : onStatusChange(paymentFormResponse);
    }, [onStatusChange, paymentMethod]);
    const handleLoad = () => {
        setLoading(false);
    };
    const handleError = () => {
        setLoading(false);
    };
    useEffect(() => {
        const handleMessage = async (e) => {
            const jsonData = e.data;
            if (typeof jsonData === 'object' &&
                jsonData.constructor.name === 'Object') {
                if (jsonData && jsonData.height) {
                    const iframe = document.querySelector('iframe');
                    if (iframe) {
                        iframe.style.height = `${jsonData.height}px`;
                    }
                }
                let responseData;
                try {
                    responseData = JSON.parse(jsonData === null || jsonData === void 0 ? void 0 : jsonData.postBackData);
                }
                catch (e) {
                    return;
                }
                if (responseData === null || responseData === void 0 ? void 0 : responseData.Token) {
                    if (jsonData.error) {
                        console.log('Error: ' + jsonData.error);
                    }
                    handlePaymentusResponse(responseData);
                    setResponse(responseData);
                }
            }
        };
        window.addEventListener('message', handleMessage);
        return () => {
            window.removeEventListener('message', handleMessage);
        };
    }, []);
    useEffect(() => {
        const preLoadForm = async () => {
            try {
                if (!(paymentData === null || paymentData === void 0 ? void 0 : paymentData.appPaymentVendorID) === null ||
                    !paymentDetails) {
                    setError(t('Missing required data to render the hosted payment form'));
                    return;
                }
                const payload = {
                    TenantID: user === null || user === void 0 ? void 0 : user.currentTenantId,
                    AppPaymentVendorID: paymentData === null || paymentData === void 0 ? void 0 : paymentData.appPaymentVendorID,
                    PaymentAmount: paymentDetails === null || paymentDetails === void 0 ? void 0 : paymentDetails.amount,
                    CurrencyCode: 'USD',
                    Customer: {
                        FirstName: paymentDetails === null || paymentDetails === void 0 ? void 0 : paymentDetails.firstName,
                        LastName: paymentDetails === null || paymentDetails === void 0 ? void 0 : paymentDetails.lastName,
                        Email: null, //paymentDetails?.email, // NULL enable one-time payment
                        Phone: paymentDetails === null || paymentDetails === void 0 ? void 0 : paymentDetails.phone
                    },
                    OriginUrl: window.location.origin,
                    Reference1: paymentDetails === null || paymentDetails === void 0 ? void 0 : paymentDetails.reference1,
                    Reference2: paymentDetails === null || paymentDetails === void 0 ? void 0 : paymentDetails.reference2,
                    Reference3: paymentDetails === null || paymentDetails === void 0 ? void 0 : paymentDetails.reference3,
                };
                const response = await getPaymentusToken(payload);
                if (response === null || response === void 0 ? void 0 : response.data) {
                    const token = response.data;
                    const urlAttributes = `${baseUrl}?authToken=${token}`;
                    setSrc(urlAttributes);
                }
            }
            catch (e) {
                console.error('Error generating iframe source URL:', e);
                setError(t('Error generating iframe source') + (e === null || e === void 0 ? void 0 : e.message));
            }
        };
        preLoadForm();
    }, [attributes, paymentData, paymentDetails, baseUrl, user]);
    return (React.createElement(React.Fragment, null, error ?
        React.createElement(React.Fragment, null, React.createElement(Typography, { variant: "subtitle1", color: "error" }, t('There was an error rendering the hosted payment form. Please check your settings and try again')), React.createElement(LayoutUnit, { unit: "xxs" }), React.createElement(Typography, { variant: "body1", color: "error" }, t('Error'), ":", error))
        :
            React.createElement(React.Fragment, null, loading && (
            // @ts-ignore
            React.createElement(Box, { sx: {
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: '100%',
                    // @ts-ignore
                    backgroundColor: 'rgba(255, 255, 255, 0.8)',
                    zIndex: 9999,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                } }, React.createElement(CircularProgress, { size: "3rem", color: "primary" }))), React.createElement("iframe", { id: "iFramePS", name: "iFramePS", src: src, scrolling: "yes", width: "100%", height: "785", frameBorder: "0", onLoad: handleLoad, onError: handleError, style: { display: loading ? 'none' : 'block' } }))));
};
//# sourceMappingURL=PaymentusForm.js.map