import { ConfigService } from "../../../configService/index.mjs";
import { TransactionUiActionTypeEnums } from "../../../enums/unitySystemEnums.mjs";
import { useHandleAxiosSnackbar } from "../../../utilities/apiHelpers.mjs";
import { apiMutate, useAxiosMutate } from "../../../utilities/useAxiosMutate.mjs";
import { SideSheet } from "../../../UI/surfaces/SideSheet.mjs";
import { PageContainer } from "../../../page/PageContainer/PageContainer.mjs";
import { FluentDialog } from "../../../UI/feedback/FluentDialog.mjs";
import { useTransactionEngine } from "../../../utilities/transactions/useTransactionEngine.mjs";
import ViewTransaction from "./sidesheets/ViewTransaction.mjs";
import AttachmentTransaction from "./sidesheets/AttachmentTransaction.mjs";
import UdpTransactionCustomPage from "./components/UdpTransactionCustomPage.mjs";
import WorkflowActions from "./sidesheets/WorkflowActions.mjs";
import { allowedExtensions } from "../../../uploader/utils/allowedFileProperties.mjs";
import DynamicTransactionDomainForm from "./components/DynamicTransactionDomainForm.mjs";
import { Attachments } from "../../../uploader/Attachments.mjs";
import EditTransaction from "./sidesheets/EditTransaction.mjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Badge } from "@material-ui/core";
import { useSnackbar } from "notistack";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpTransactionsPage/UdpTransactionSidesheet.jsx
const UdpTransactionSidesheet = (props) => {
	const { openStates, handleSidesheet, handleAttachmentTransaction, transaction, transactionTypeId, domainName, refreshGridData, label: sidesheetLabel, hideSaveChanges, catalogObject } = props;
	const [sidesheetLoading, setSidesheetLoading] = useState(false);
	const [closingTransactionLoading, setClosingTransactionLoading] = useState(false);
	const [editTransactionopenInnerSidesheetState, setEditTransactionOpenInnerSidesheetState] = useState({
		attachments: false,
		workflowActions: false,
		notes: false
	});
	const [dialogOpen, setDialogOpen] = useState(false);
	const [unsavedChangesDialogOpen, setUnsavedChangesDialogOpen] = useState(false);
	const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
	const [createTransactionOpenInnerSidesheetState, setCreateTransactionOpenInnerSidesheetState] = useState({ attachments: false });
	const [attachmentType, setAttachmentType] = useState(null);
	const [currentAttachments, setCurrentAttachments] = useState([]);
	const [attachmentProgress, setAttachmentProgress] = useState(false);
	const [transactionAttachments, setTransactionAttachments] = useState([]);
	const [filePreview, setFilePreview] = useState(false);
	const [sidesheetPrimaryButtonDisabled, setSidesheetPrimaryButtonDisabled] = useState(false);
	const [sidesheetSecondaryButtonDisabled, setSidesheetSecondaryButtonDisabled] = useState(false);
	const { handleSuccessSnackbar, handleErrorSnackbar } = useHandleAxiosSnackbar();
	const { hasClosedStatus, checkIfTransactionIsClosed, getTransactionTypeLabel, getUiActionRenderParameters, transactionTypePageConfiguration, closedStatuses } = useTransactionEngine(transactionTypeId);
	const { t } = useTranslation();
	const formRef = useRef(null);
	const createdTransactionIdRef = useRef(null);
	const attachmentRef = useRef();
	const sidesheetWidth = openStates?.width ?? 800;
	const transactionTypeEntry = transaction?.entityBusinessObject;
	const { enqueueSnackbar } = useSnackbar();
	const [{ data: transactionAttachmentTypes }, fetchTransactionAttachmentType] = useAxiosMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachmentType/search`, {
		method: "post",
		data: {
			pageSize: 50,
			filterElements: [{
				searchField: "TransactionTypeId",
				searchValue: transactionTypeId,
				searchOperator: "="
			}]
		}
	});
	const handleDialogClose = () => {
		setDialogOpen(false);
	};
	const handleUnsavedChangesDialogClose = () => {
		setUnsavedChangesDialogOpen(false);
	};
	const handleResetAttachmentState = useCallback((resetSavedAttachmentsState) => {
		if (resetSavedAttachmentsState) {
			setAttachmentType(null);
			setCurrentAttachments([]);
		}
		setAttachmentProgress(false);
		setTransactionAttachments([]);
		setFilePreview(false);
	}, []);
	const executeCloseTransaction = useCallback(async () => {
		if ((await apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/${transaction?.transactionId}/closeTransaction`, { method: "post" }))?.status === 200) {
			handleSidesheet("edit", false);
			refreshGridData();
			handleSuccessSnackbar(t(`Transaction has been closed successfully`));
		} else handleErrorSnackbar(new Error(t(`Error closing Transaction. Please try again later.`)));
	}, [
		transaction,
		refreshGridData,
		handleSidesheet,
		handleSuccessSnackbar,
		handleErrorSnackbar,
		t
	]);
	const handleConfirmCloseTransactionDialog = useCallback(async () => {
		try {
			setClosingTransactionLoading(true);
			await executeCloseTransaction();
		} catch (error) {
			handleErrorSnackbar(error);
		} finally {
			setClosingTransactionLoading(false);
			handleDialogClose();
		}
	}, [executeCloseTransaction, handleErrorSnackbar]);
	const formattedBusinesskey = transactionTypeEntry?.businessObjectKey?.split("|")?.pop();
	const handleTransactionCreationSuccess = useCallback((response_0) => {
		createdTransactionIdRef.current = response_0?.data?.transactionId ?? null;
		handleSidesheet("add", false);
		handleResetAttachmentState(true);
	}, [handleSidesheet, handleResetAttachmentState]);
	const handleTransactionRevisionCreationSuccess = useCallback((response_1) => {
		handleSidesheet("createRevision", false);
		refreshGridData();
	}, [handleSidesheet, refreshGridData]);
	const handleFilesSelectedForUpload = useCallback(() => {
		setCreateTransactionOpenInnerSidesheetState({ attachments: false });
		enqueueSnackbar(`${currentAttachments.length} file(s) added for upload`, {
			variant: "success",
			anchorOrigin: {
				vertical: "top",
				horizontal: "center"
			}
		});
	}, [enqueueSnackbar, currentAttachments.length]);
	const handleUploadFilesForCreateTransaction = useCallback(async (transactionId) => {
		if (!currentAttachments.length) throw new Error("No files added for upload");
		const formData = new FormData();
		currentAttachments.forEach((file) => formData.append("files", file));
		formData.append("attachmentTypeId", attachmentType.transactionAttachmentTypeId);
		try {
			setAttachmentProgress(true);
			await apiMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/transaction/${transactionId}/upload`, {
				method: "post",
				headers: {
					transactionId,
					attachmentTypeId: attachmentType.transactionAttachmentTypeId
				},
				data: formData
			});
			setCurrentAttachments([]);
			setCreateTransactionOpenInnerSidesheetState({ attachments: false });
			enqueueSnackbar("Files uploaded successfully", {
				variant: "success",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
		} catch (error_0) {
			enqueueSnackbar(`File upload failed: We encountered a system error. Please try again or contact support if the issue persists.`, {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
			throw error_0;
		} finally {
			setAttachmentProgress(false);
		}
	}, [
		attachmentType,
		currentAttachments,
		enqueueSnackbar,
		setCurrentAttachments,
		setAttachmentProgress
	]);
	const handleTransactionCreation = useCallback(async () => {
		setSidesheetLoading(true);
		createdTransactionIdRef.current = null;
		await formRef.current?.form?.submit();
		const newTransactionId = createdTransactionIdRef.current;
		if (newTransactionId && currentAttachments.length > 0) await handleUploadFilesForCreateTransaction(newTransactionId);
		refreshGridData();
		setSidesheetLoading(false);
	}, [
		formRef,
		currentAttachments.length,
		handleUploadFilesForCreateTransaction,
		refreshGridData
	]);
	const handleCreateRevision = useCallback(async () => {
		setSidesheetLoading(true);
		await formRef.current?.form?.submit();
		setSidesheetLoading(false);
	}, [formRef]);
	const handleNextStepsAction = useCallback(() => {
		if (!hasUnsavedChanges) setEditTransactionOpenInnerSidesheetState({ workflowAction: true });
		else setUnsavedChangesDialogOpen(true);
	}, [hasUnsavedChanges]);
	const handleConfirmUnsavedChangesDialog = useCallback(() => {
		setUnsavedChangesDialogOpen(false);
		setEditTransactionOpenInnerSidesheetState({ workflowAction: true });
	}, []);
	const pdfViewPageId = useMemo(() => {
		return getUiActionRenderParameters(TransactionUiActionTypeEnums.Render_View_Pdf_Page)?.pageId;
	}, [getUiActionRenderParameters]);
	const viewTransactionPage = useMemo(() => {
		if (pdfViewPageId) return /* @__PURE__ */ React.createElement(PageContainer, {
			pageId: pdfViewPageId,
			widgetParams: { transaction }
		});
		else return /* @__PURE__ */ React.createElement(ViewTransaction, { transaction });
	}, [transaction, pdfViewPageId]);
	const transactionIsClosed = useMemo(() => {
		return checkIfTransactionIsClosed(transaction);
	}, [checkIfTransactionIsClosed, transaction]);
	const transactionLabel = useMemo(() => {
		return ` ${getTransactionTypeLabel(transaction) ?? `${domainName} ${formattedBusinesskey ?? ""}`}`;
	}, [
		getTransactionTypeLabel,
		transaction,
		formattedBusinesskey,
		domainName
	]);
	const sheetLabel = useMemo(() => {
		if (sidesheetLabel) return sidesheetLabel;
		return transactionLabel;
	}, [sidesheetLabel, transactionLabel]);
	const transactionCreatePageId = useMemo(() => {
		return getUiActionRenderParameters(TransactionUiActionTypeEnums.Render_Create_Transaction_Page)?.pageId;
	}, [getUiActionRenderParameters]);
	const sidesheetList = useMemo(() => {
		return [
			{
				open: openStates.addTransaction,
				closeSheet: () => {
					handleSidesheet("add", false);
					handleResetAttachmentState(true);
				},
				title: sheetLabel?.trim() || domainName,
				width: sidesheetWidth,
				onSubmit: handleTransactionCreation,
				children: /* @__PURE__ */ React.createElement(React.Fragment, null, transactionCreatePageId ? /* @__PURE__ */ React.createElement(UdpTransactionCustomPage, {
					transactionTypeId,
					transactionUiActionType: TransactionUiActionTypeEnums.Render_Create_Transaction_Page,
					formRef,
					onSubmitSuccess: handleTransactionCreationSuccess,
					refreshGridData,
					additionalPageParms: { sidesheetParams: {
						setSidesheetPrimaryButtonDisabled,
						setSidesheetSecondaryButtonDisabled
					} }
				}) : /* @__PURE__ */ React.createElement(DynamicTransactionDomainForm, {
					transaction,
					formRef,
					domainName,
					transactionTypeId,
					transactionUiActionType: TransactionUiActionTypeEnums.Render_Create_Transaction_Page,
					onSubmitSuccess: handleTransactionCreationSuccess,
					catalogObject
				}), /* @__PURE__ */ React.createElement(SideSheet, {
					key: "Create Transaction: Add Attachment",
					open: createTransactionOpenInnerSidesheetState?.attachments,
					width: 600,
					title: t("Add Attachment"),
					onClose: () => {
						setCreateTransactionOpenInnerSidesheetState({ attachments: false });
						handleResetAttachmentState(true);
					},
					buttonLabel: t("Save"),
					buttonOneDisabled: !attachmentType || currentAttachments.length <= 0,
					onSubmit: handleFilesSelectedForUpload,
					color: "primary"
				}, /* @__PURE__ */ React.createElement(Attachments, {
					attachmentTypes: transactionAttachmentTypes,
					attachmentType,
					setAttachmentType,
					attachmentProgress,
					setAttachmentProgress,
					currentAttachments,
					setCurrentAttachments,
					transaction,
					previousAttachments: transactionAttachments,
					setPreviousAttachments: setTransactionAttachments,
					MAX_FILE_SIZE_MB: 30,
					allowedExtensions,
					filePreview,
					setFilePreview
				}))),
				buttonLabel: "Add",
				buttonTwoLabel: /* @__PURE__ */ React.createElement(Badge, {
					badgeContent: currentAttachments?.length,
					color: "primary"
				}, "Add Attachment"),
				buttonTwoAction: () => setCreateTransactionOpenInnerSidesheetState({ attachments: true })
			},
			{
				open: openStates.viewTransaction,
				closeSheet: () => handleSidesheet("view", false),
				title: sheetLabel + " - Preview",
				width: sidesheetWidth,
				children: viewTransactionPage,
				buttonLabel: !pdfViewPageId ? "Download" : null
			},
			{
				open: openStates.attachmentTransaction,
				closeSheet: () => handleSidesheet("view", false),
				title: "Attachment for " + sheetLabel,
				width: sidesheetWidth,
				buttonLabel: "Download",
				onSubmit: () => {
					if (attachmentRef.current) attachmentRef.current.downloadSelectedFile();
				},
				children: /* @__PURE__ */ React.createElement(AttachmentTransaction, {
					handleAttachmentTransaction,
					attachmentRef,
					transaction,
					domainName,
					setSidesheetLoading
				})
			},
			{
				open: openStates.workflowAction,
				closeSheet: () => handleSidesheet("action", false),
				title: `Workflow Actions - ${sheetLabel}`,
				width: sidesheetWidth,
				children: /* @__PURE__ */ React.createElement(WorkflowActions, {
					transaction,
					closeSideSheet: () => {
						handleSidesheet("action", false);
					},
					refreshGridData,
					handleSidesheet
				})
			},
			{
				open: openStates.editTransaction,
				closeSheet: () => {
					handleSidesheet("edit", false);
					handleResetAttachmentState(true);
				},
				title: `Edit ${sheetLabel}`,
				width: sidesheetWidth,
				buttonLabel: "Next Steps",
				buttonOneDisabled: transactionIsClosed,
				onSubmit: handleNextStepsAction,
				buttonTwoLabel: closedStatuses?.length === 1 ? "Close " + domainName : null,
				buttonTwoDisabled: transactionIsClosed || !hasClosedStatus,
				buttonTwoAction: () => setDialogOpen(true),
				children: /* @__PURE__ */ React.createElement(EditTransaction, {
					transaction,
					transactionTypeId,
					transactionIsClosed,
					openInnerSidesheetState: editTransactionopenInnerSidesheetState,
					setOpenInnerSidesheetState: setEditTransactionOpenInnerSidesheetState,
					refreshGridData,
					closeSideSheet: () => {
						handleSidesheet("edit", false);
						handleResetAttachmentState(true);
					},
					setSidesheetLoading,
					setHasUnsavedChanges,
					attachmentType,
					setAttachmentType,
					currentAttachments,
					setCurrentAttachments,
					attachmentProgress,
					setAttachmentProgress,
					transactionAttachmentTypes,
					transactionAttachments,
					setTransactionAttachments,
					filePreview,
					setFilePreview,
					domainName,
					additionalPageParms: { sidesheetParams: {
						setSidesheetPrimaryButtonDisabled,
						setSidesheetSecondaryButtonDisabled
					} },
					hideSaveChanges: hideSaveChanges || transactionTypePageConfiguration?.hideSaveChanges,
					catalogObject
				})
			},
			{
				open: openStates.createRevision,
				closeSheet: () => handleSidesheet("createRevision", false),
				title: `Create Revision for ${domainName}`,
				width: sidesheetWidth,
				onSubmit: handleCreateRevision,
				children: /* @__PURE__ */ React.createElement(UdpTransactionCustomPage, {
					transactionTypeId,
					transactionUiActionType: TransactionUiActionTypeEnums.Render_Create_Revision_Page,
					formRef,
					transaction,
					onSubmitSuccess: handleTransactionRevisionCreationSuccess,
					refreshGridData,
					additionalPageParms: { sidesheetParams: {
						setSidesheetPrimaryButtonDisabled,
						setSidesheetSecondaryButtonDisabled
					} }
				}),
				buttonLabel: "Create Revision"
			}
		];
	}, [
		openStates,
		handleSidesheet,
		handleAttachmentTransaction,
		transaction,
		domainName,
		editTransactionopenInnerSidesheetState,
		setEditTransactionOpenInnerSidesheetState,
		sheetLabel,
		refreshGridData,
		transactionTypeId,
		handleTransactionCreation,
		handleTransactionCreationSuccess,
		hasClosedStatus,
		handleCreateRevision,
		transactionIsClosed,
		viewTransactionPage,
		pdfViewPageId,
		sidesheetWidth,
		handleNextStepsAction,
		transactionCreatePageId,
		createTransactionOpenInnerSidesheetState,
		t,
		attachmentType,
		setAttachmentType,
		currentAttachments,
		setCurrentAttachments,
		attachmentProgress,
		setAttachmentProgress,
		transactionAttachmentTypes,
		transactionAttachments,
		setTransactionAttachments,
		filePreview,
		setFilePreview,
		handleResetAttachmentState,
		handleFilesSelectedForUpload,
		handleTransactionRevisionCreationSuccess,
		hideSaveChanges,
		transactionTypePageConfiguration
	]);
	useEffect(() => {
		if ((openStates?.addTransaction || openStates?.editTransaction) && !transactionAttachmentTypes) {
			setAttachmentProgress(true);
			fetchTransactionAttachmentType().then(() => {
				setAttachmentProgress(false);
			});
		}
	}, [
		fetchTransactionAttachmentType,
		transactionAttachmentTypes,
		openStates.addTransaction,
		openStates.editTransaction
	]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, openStates && sidesheetList.map((item) => {
		return /* @__PURE__ */ React.createElement(SideSheet, {
			key: item.title,
			open: item.open,
			width: sidesheetWidth,
			title: item.title,
			onClose: item.closeSheet,
			noPadding: openStates.attachmentTransaction || openStates.editTransaction,
			buttonLabel: item?.buttonLabel,
			onSubmit: item?.onSubmit,
			color: "primary",
			buttonTwoLabel: item?.buttonTwoLabel,
			buttonTwoAction: item?.buttonTwoAction,
			buttonOneDisabled: item?.buttonOneDisabled || sidesheetPrimaryButtonDisabled,
			buttonTwoDisabled: item?.buttonTwoDisabled || sidesheetSecondaryButtonDisabled,
			progress: sidesheetLoading,
			variant: "indeterminate"
		}, /* @__PURE__ */ React.createElement("div", null, item.children));
	}), /* @__PURE__ */ React.createElement(FluentDialog, {
		title: t(`Close Transaction`),
		message: `Are you sure you want to close transaction for ${transaction?.entityBusinessKey || ""}?`,
		labelOne: t("Confirm"),
		actionOne: handleConfirmCloseTransactionDialog,
		labelTwo: t("Cancel"),
		actionTwo: handleDialogClose,
		open: dialogOpen,
		handleClose: handleDialogClose,
		loading: closingTransactionLoading
	}), /* @__PURE__ */ React.createElement(FluentDialog, {
		title: t(`Unsaved Changes`),
		message: `You have unsaved changes. Are you sure you want to go to next steps?`,
		labelOne: t("Confirm"),
		actionOne: handleConfirmUnsavedChangesDialog,
		labelTwo: t("Cancel"),
		actionTwo: handleUnsavedChangesDialogClose,
		open: unsavedChangesDialogOpen,
		handleClose: handleUnsavedChangesDialogClose,
		loading: closingTransactionLoading
	}));
};
//#endregion
export { UdpTransactionSidesheet as default };

//# sourceMappingURL=UdpTransactionSidesheet.mjs.map