import { Form } from "../../../../utilities/form/Form.mjs";
import { FormSpy } from "../../../../utilities/form/FormSpy.mjs";
import { TransactionUiActionTypeEnums } from "../../../../enums/unitySystemEnums.mjs";
import { useHandleAxiosSnackbar } from "../../../../utilities/apiHelpers.mjs";
import { apiMutate } from "../../../../utilities/useAxiosMutate.mjs";
import { PageContainer } from "../../../../page/PageContainer/PageContainer.mjs";
import { useTransactionEngine } from "../../../../utilities/transactions/useTransactionEngine.mjs";
import React, { useCallback, useMemo, useState } from "react";
import { ConfigService } from "udp-react-stencil-component-library";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpTransactionsPage/components/UdpTransactionCustomPage.jsx
const UdpTransactionCustomPage = (props) => {
	const { pageId, transactionTypeId, transactionUiActionType, formRef, refetchTransaction, transaction, transactionTypeTransactionActionId, setHasUnsavedChanges, onSubmitSuccess, refreshGridData, additionalPageParms = {} } = props;
	const [pageOnSubmitSuccess, setPageOnSubmitSuccess] = useState(null);
	const { getUiActionRenderParameters, getHiddenFields, getRequiredFields } = useTransactionEngine(transactionTypeId);
	const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
	const { t } = useTranslation();
	const executeCreateTransactionAction = useCallback(async (data) => apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/transactionType/${transactionTypeId}/create`, { method: "post" }, data), [transactionTypeId]);
	const executeSaveChanges = useCallback(async (data_0) => apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/${transaction?.transactionId}/saveChanges`, { method: "put" }, data_0), [transaction?.transactionId]);
	const executeCreateRevision = useCallback(async (data_1) => apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/${transaction?.transactionId}/createRevision`, { method: "post" }, data_1), [transaction?.transactionId]);
	const executeSubmitCustomAction = useCallback(async (data_2) => apiMutate(ConfigService.productV1ApiUrl, `udptransactiontypeTransactionAction/${transactionTypeTransactionActionId}/transaction/${transaction.transactionId}/submit`, { method: "post" }, data_2), [transactionTypeTransactionActionId, transaction?.transactionId]);
	const executeSubmitActionApi = useCallback(async (data_3, actionApiId) => apiMutate(ConfigService.productV1ApiUrl, `udpTransactionWorkflowActionApi/${actionApiId}/transaction/${transaction.transactionId}/submit`, { method: "post" }, data_3), [transaction?.transactionId]);
	const onSubmit = useCallback(async (values) => {
		try {
			const request = { data: values };
			const actionApiId_0 = transactionUiActionType ? getUiActionRenderParameters(transactionUiActionType)?.actionApiId : null;
			let response = null;
			let message = "";
			let errorMessagePart = "";
			if (transactionUiActionType === TransactionUiActionTypeEnums.Render_Create_Transaction_Page) {
				if (actionApiId_0) response = await executeSubmitActionApi(request, actionApiId_0);
				else response = await executeCreateTransactionAction(request);
				message = "Transaction has been created successfully";
				errorMessagePart = "creating";
			} else if (transactionUiActionType === TransactionUiActionTypeEnums.Render_Transaction_Details_Page) {
				if (actionApiId_0) response = await executeSubmitActionApi(request, actionApiId_0);
				else response = await executeSaveChanges(request);
				message = "Transaction has been saved successfully";
				errorMessagePart = "saving";
			} else if (transactionUiActionType === TransactionUiActionTypeEnums.Render_Create_Revision_Page) {
				if (actionApiId_0) response = await executeSubmitActionApi(request, actionApiId_0);
				else response = await executeCreateRevision(request);
				message = "Revision has been created successfully";
				errorMessagePart = "creating revision for";
			} else if (!!transactionTypeTransactionActionId) {
				response = await executeSubmitCustomAction(request);
				message = "Action has been submitted successfully";
				errorMessagePart = "submitting action for";
			}
			const { status, data: data_4 } = response || {};
			const apiResult = data_4?.actionApiResult;
			if (status === 200) {
				if (!apiResult || apiResult.success) {
					handleSuccessSnackbar(t(`${message}`));
					onSubmitSuccess?.(response);
					pageOnSubmitSuccess?.(data_4);
				} else if (apiResult?.errorMessage) handleErrorSnackbar(new Error(apiResult.errorMessage));
			} else {
				const defaultError = t(`Error ${errorMessagePart} Transaction. Please try again later.`);
				handleErrorSnackbar(new Error(defaultError));
			}
		} catch (error) {
			handleErrorSnackbar(error);
		} finally {
			if (setHasUnsavedChanges) {
				formRef.current?.form?.restart(values);
				setHasUnsavedChanges(false);
			}
			if (refetchTransaction) refetchTransaction();
		}
	}, [
		executeCreateTransactionAction,
		executeSaveChanges,
		executeCreateRevision,
		handleErrorSnackbar,
		handleSuccessSnackbar,
		transactionUiActionType,
		executeSubmitCustomAction,
		t,
		transactionTypeTransactionActionId,
		setHasUnsavedChanges,
		formRef,
		onSubmitSuccess,
		refetchTransaction,
		pageOnSubmitSuccess,
		executeSubmitActionApi,
		getUiActionRenderParameters
	]);
	const isFieldRequired = useCallback((fieldName) => {
		return getRequiredFields(transaction)?.includes(fieldName);
	}, [getRequiredFields, transaction]);
	const isFieldHidden = useCallback((fieldName_0) => {
		return getHiddenFields(transaction)?.includes(fieldName_0);
	}, [getHiddenFields, transaction]);
	const transactionPageId = useMemo(() => {
		if (pageId) return pageId;
		return getUiActionRenderParameters(transactionUiActionType)?.pageId;
	}, [
		getUiActionRenderParameters,
		transactionUiActionType,
		pageId
	]);
	if (!transactionPageId) return null;
	return /* @__PURE__ */ React.createElement(Form, {
		onSubmit,
		ref: formRef
	}, /* @__PURE__ */ React.createElement(FormSpy, { subscription: { dirty: true } }, ({ dirty }) => {
		if (setHasUnsavedChanges) setHasUnsavedChanges(dirty);
	}), /* @__PURE__ */ React.createElement(PageContainer, {
		pageId: transactionPageId,
		updateLocationState: false,
		widgetParams: {
			transaction,
			isFieldRequired,
			isFieldHidden,
			refreshTransactionGrid: refreshGridData,
			setOnSubmitSuccess: setPageOnSubmitSuccess,
			...additionalPageParms
		}
	}));
};
//#endregion
export { UdpTransactionCustomPage as default };

//# sourceMappingURL=UdpTransactionCustomPage.mjs.map