import { ConfigService } from "../../../../configService/index.mjs";
import { useUser } from "../../../auth/useUser.mjs";
import { apiMutate } from "../../../useAxiosMutate.mjs";
import { LayoutUnit } from "../../../../layout/LayoutUnit.mjs";
import { PaymentTenderTypeEnum } from "../../../../enums/paymentTenderTypeEnum.mjs";
import { PaymentVendorFactoryEnum } from "../../../../enums/paymentVendorFactoryEnum.mjs";
import { CircularProgress as CircularProgress$1 } from "../../../../UI/loading/CircularProgress.mjs";
import React, { useCallback, useEffect, useState } from "react";
import { Box, Typography } from "@material-ui/core";
import { useTranslation } from "react-i18next";
import { v4 } from "uuid";
//#region src/utilities/form/paymentForm/vendorsForms/PaymentusForm.tsx
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(v4());
	const [paymentTokenIDGuid] = useState(v4());
	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
		}, {});
	}, []);
	useCallback(async (payload_0) => {
		if (!payload_0) return null;
		const PostURL = paymentMethod === PaymentTenderTypeEnum.CreditCard ? "PaymentTokenCreditCard/ByPass" : "PaymentTokenECheck/CreateByPass";
		return apiMutate(ConfigService.pgV1ApiUrl, `${PostURL}`, {
			method: "POST",
			data: payload_0
		}, {});
	}, []);
	/**
	* handleFiservResponse
	*
	* @param {*} response
	*/
	const handlePaymentusResponse = useCallback((response_0) => {
		const paymentFormResponse = {
			isValid: !response_0?.error,
			payload: response_0,
			message: response_0?.Token,
			errorCode: response_0?.error,
			errorMessage: response_0?.error,
			selectedHostedPayment: PaymentVendorFactoryEnum.Paymentus
		};
		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?.postBackData);
				} catch (e_0) {
					return;
				}
				if (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?.appPaymentVendorID === null || !paymentDetails) {
					setError(t("Missing required data to render the hosted payment form"));
					return;
				}
				const response_1 = await getPaymentusToken({
					TenantID: user?.currentTenantId,
					AppPaymentVendorID: paymentData?.appPaymentVendorID,
					PaymentAmount: paymentDetails?.amount,
					CurrencyCode: "USD",
					Customer: {
						FirstName: paymentDetails?.firstName,
						LastName: paymentDetails?.lastName,
						Email: null,
						Phone: paymentDetails?.phone
					},
					OriginUrl: window.location.origin,
					Reference1: paymentDetails?.reference1,
					Reference2: paymentDetails?.reference2,
					Reference3: paymentDetails?.reference3
				});
				if (response_1?.data) setSrc(`${baseUrl}?authToken=${response_1.data}`);
			} catch (e_1) {
				console.error("Error generating iframe source URL:", e_1);
				setError(t("Error generating iframe source") + e_1?.message);
			}
		};
		preLoadForm();
	}, [
		attributes,
		paymentData,
		paymentDetails,
		baseUrl,
		user
	]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, error ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Typography, {
		variant: "subtitle1",
		color: "error"
	}, t("There was an error rendering the hosted payment form. Please check your settings and try again"), ":"), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "xxs" }), /* @__PURE__ */ React.createElement(Typography, {
		variant: "body1",
		color: "error"
	}, t("Error"), ":", error)) : /* @__PURE__ */ React.createElement(React.Fragment, null, loading && /* @__PURE__ */ React.createElement(Box, { sx: {
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		backgroundColor: "rgba(255, 255, 255, 0.8)",
		zIndex: 9999,
		display: "flex",
		alignItems: "center",
		justifyContent: "center"
	} }, /* @__PURE__ */ React.createElement(CircularProgress$1, {
		size: "3rem",
		color: "primary"
	})), /* @__PURE__ */ React.createElement("iframe", {
		id: "iFramePS",
		name: "iFramePS",
		src,
		scrolling: "yes",
		width: "100%",
		height: "785",
		frameBorder: "0",
		onLoad: handleLoad,
		onError: handleError,
		style: { display: loading ? "none" : "block" }
	})));
};
//#endregion
export { PaymentusForm };

//# sourceMappingURL=PaymentusForm.mjs.map