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, useTheme } from "@material-ui/core";
import { useTranslation } from "react-i18next";
//#region src/utilities/form/paymentForm/vendorsForms/ICheckForm.tsx
const defaultCssStyles = (theme) => `
  body {
    background: ${theme.palette.background.default};
  }
  payment {
    padding: 1rem;
    max-width: none;
    background: ${theme.palette.background.paper};
    border: none;
    box-shadow: none;
    color: ${theme.palette.text.primary};
  }
  paymentNumber {
    border: 1px solid ${theme.palette.divider};
  }
  input[type='button'],
  input[type='reset'],
  input[type='submit'] {
    background-color: ${theme.palette.primary.main};
    font-size: 14px;
    height: 40px;
    border-radius: 0px;
    border: none;
  }
`.trim();
/**
* `ICheckForm` Component
*
* Renders an iframe for payment processing via the iCheckGateway. Depending on the payment method, it dynamically generates the iframe URL with the appropriate query parameters. The component also listens for messages from the iframe, handling payment data or errors.
*
* @param {Object} props The properties passed to the component.
* @param {PaymentTenderTypeEnum} [paymentMethod=PaymentTenderTypeEnum.CreditCard] Specifies the type of payment method, influencing the iframe endpoint.
* @param {Object} [onStatusChange=null] Callback function to handle the status change event.
* @param {Object} [paymentDetails=null] An object containing customer details such as firstName, lastName, email, etc.
* @param {string} [baseUrl="https://iframe.icheckgateway.com"] The base URL for the payment gateway iframe.
* @param {string} [customCss=defaultCssStyles] Custom CSS styles to be applied within the iframe.
* @param {Object} [attributes=null] An object containing additional payment attributes such as appId, appSecret, custId, etc. These are dynamically appended to the iframe URL as query parameters.
* @param {string} [attributes.appId] Application ID for the payment gateway.
* @param {string} [attributes.appSecret] Application secret for the payment gateway.
* @param {string} [attributes.custId] Customer ID.
* @param {string} [attributes.saveTokenDisabled] Flag to disable token saving.
* @param {string} [attributes.firstName] Customer's first name.
* @param {string} [attributes.lastName] Customer's last name.
* @param {string} [attributes.email] Customer's email address.
* @param {string} [attributes.company] Customer's company name.
* @param {string} [attributes.street1] Customer's street address line 1.
* @param {string} [attributes.street2] Customer's street address line 2.
* @param {string} [attributes.city] Customer's city.
* @param {string} [attributes.custom1] A custom field for additional data.
* @param {string} [attributes.amount] Payment amount.
* @param {string} [attributes.salesTax] Applicable sales tax.
* @param {string} [attributes.entryClassCode] Entry class code for the transaction.
* @param {string} [attributes.css] Custom CSS for the iframe content.
* @param {string} [attributes.hostedURL="https://iframe.icheckgateway.com"] Hosted URL; defaults to the base URL but can be overridden.
*
* @return {React.Component} The `ICheckForm` component renders an iframe for payment processing and displays the payment response.
*/
const ICheckForm = ({ paymentMethod = PaymentTenderTypeEnum.CreditCard, onStatusChange = null, paymentDetails = null, baseUrl = "https://iframe.icheckgateway.com", customCss = "", attributes = null, paymentData = null }) => {
	const iframePaymentMethod = paymentMethod === PaymentTenderTypeEnum.CreditCard ? "iFrameCC" : "iFrameBA";
	const [src, setSrc] = useState(`${baseUrl}/${iframePaymentMethod}.aspx?`);
	const [response, setResponse] = useState({});
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState("");
	const { t } = useTranslation();
	const defaultCss = defaultCssStyles(useTheme());
	/**
	* handleFiservResponse
	*
	* @param {*} response
	*/
	const handleICheckResponse = useCallback((response_0) => {
		const isError = response_0?.error;
		const payload = JSON.stringify(response_0, null, 2);
		const paymentFormResponse = {
			isValid: !isError,
			payload,
			message: response_0?.token,
			errorCode: response_0?.error,
			errorMessage: response_0?.error,
			selectedHostedPayment: PaymentVendorFactoryEnum.ICheck
		};
		onStatusChange?.(paymentFormResponse);
	}, [onStatusChange, paymentMethod]);
	const handleLoad = () => {
		setLoading(false);
	};
	const handleError = () => {
		setLoading(false);
	};
	useEffect(() => {
		try {
			let urlAttributes = src;
			let queryParams = "";
			if (paymentDetails) {
				const mergedDetails = {
					...attributes,
					...paymentDetails
				};
				const baseUrl_0 = attributes?.baseUrl + `/${iframePaymentMethod}.aspx`;
				delete mergedDetails.baseUrl;
				queryParams = `${baseUrl_0}?${Object.keys(mergedDetails).filter((key) => mergedDetails[key] !== "" && mergedDetails[key] != null).map((key_0) => `${encodeURIComponent(key_0)}=${encodeURIComponent(mergedDetails[key_0])}`).join("&")}`;
			}
			queryParams += `&css=${encodeURIComponent(customCss || defaultCss)}`;
			if (paymentDetails) urlAttributes = queryParams;
			else urlAttributes += queryParams;
			setSrc(urlAttributes);
		} catch (e) {
			console.error("Error generating iframe source URL:", e);
			setError(t("Error generating iframe source") + e?.message);
		}
	}, [
		attributes,
		paymentDetails,
		baseUrl,
		iframePaymentMethod,
		customCss
	]);
	useEffect(() => {
		const handleMessage = (e_0) => {
			const jsonData = e_0.data;
			if (typeof jsonData === "object" && jsonData.constructor.name === "Object") {
				if (jsonData.source === "iCheck") {
					if (jsonData.error) console.log("Error: " + jsonData.error);
					handleICheckResponse(jsonData);
					setResponse(jsonData);
				}
			}
		};
		window.addEventListener("message", handleMessage);
		return () => {
			window.removeEventListener("message", handleMessage);
		};
	}, []);
	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%",
			zIndex: 9999,
			display: "flex",
			alignItems: "center",
			justifyContent: "center"
		},
		style: { backgroundColor: "rgba(255, 255, 255, 0.8)" }
	}, /* @__PURE__ */ React.createElement(CircularProgress$1, {
		size: "3rem",
		color: "primary"
	})), /* @__PURE__ */ React.createElement("iframe", {
		id: "iFrameBA",
		name: "iFrameBA",
		src,
		scrolling: "yes",
		width: "100%",
		height: "500",
		frameBorder: "0",
		onLoad: handleLoad,
		onError: handleError,
		style: { display: loading ? "none" : "block" }
	})));
};
//#endregion
export { ICheckForm };

//# sourceMappingURL=ICheckForm.mjs.map