import { FluentButton } from "../../../../UI/inputs/buttons/FluentButton.mjs";
import { ConfigService } from "../../../../configService/index.mjs";
import { TransactionUiActionTypeEnums } from "../../../../enums/unitySystemEnums.mjs";
import { apiMutate, useAxiosMutate } from "../../../../utilities/useAxiosMutate.mjs";
import { FluentIcon } from "../../../../utilities/iconLibrary/FluentIcon.mjs";
import { SideSheet } from "../../../../UI/surfaces/SideSheet.mjs";
import { useAxiosGet } from "../../../../utilities/useAxiosGet.mjs";
import { Divider } from "../../../../UI/utilityDisplay/Divider.mjs";
import { UdpTabs } from "../../../../UI/navigation/tabs/UdpTabs.mjs";
import { UdpTabPanel } from "../../../../UI/navigation/tabs/UdpTabPanel.mjs";
import { useTransactionEngine } from "../../../../utilities/transactions/useTransactionEngine.mjs";
import UdpTransactionCustomPage from "../components/UdpTransactionCustomPage.mjs";
import WorkflowActions from "./WorkflowActions.mjs";
import { allowedExtensions } from "../../../../uploader/utils/allowedFileProperties.mjs";
import EditTransactionHeaderItem from "./EditTransactionHeaderItem.mjs";
import TransactionTimeline from "../components/transactionHistory/TransactionTimeline.mjs";
import { TransactionAttachments } from "../components/transactionAttachment/TransactionAttachments.mjs";
import { TransactionNoteForm } from "../components/transactionNote/TransactionNoteForm.mjs";
import { TransactionNotes } from "../components/transactionNote/TransactionNotes.mjs";
import { TRANSACTION_TAB } from "./enum.mjs";
import EditTransactionDetailsFooterItem from "../components/EditTransactionDetailsFooterItem.mjs";
import DynamicTransactionDomainForm from "../components/DynamicTransactionDomainForm.mjs";
import { Attachments } from "../../../../uploader/Attachments.mjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useSnackbar } from "notistack";
import { AddIcon } from "@fluentui/react-icons";
import { useTranslation } from "react-i18next";
import "./EditTransaction.css";
//#region src/udp/pages/UdpTransactionsPage/sidesheets/EditTransaction.jsx
const EditTransaction = (props) => {
	const { transaction: initialTransaction, transactionTypeId, transactionIsClosed, openInnerSidesheetState, setOpenInnerSidesheetState, refreshGridData, closeSideSheet, setSidesheetLoading, setHasUnsavedChanges, domainName, attachmentType, setAttachmentType, currentAttachments, setCurrentAttachments, attachmentProgress, setAttachmentProgress, transactionAttachmentTypes, transactionAttachments, setTransactionAttachments, filePreview, setFilePreview, additionalPageParms, hideSaveChanges, catalogObject } = props;
	const { t } = useTranslation();
	const [selectedTab, setSelectedTab] = useState(0);
	const [transaction, setTransaction] = useState(initialTransaction);
	const [refreshNotes, setRefreshNotes] = useState(false);
	const [{ data: noteTypes, loading: fetchNoteTypesLoading }] = useAxiosGet(ConfigService.productV1ApiUrl, `UdpNoteType`, {});
	const { getUiActionRenderParameters, transactionTypeStatusColorsMap } = useTransactionEngine(transactionTypeId);
	const refetchTransaction = useCallback(async () => {
		setSidesheetLoading(true);
		const response = await apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/${initialTransaction?.transactionId}/full`, { method: "get" });
		if (response?.status === 200) {
			setTransaction(response.data);
			transactionTimelineRef.current?.refresh();
		}
		setSidesheetLoading(false);
	}, [initialTransaction?.transactionId, setSidesheetLoading]);
	const formRef = useRef(null);
	const transactionNoteFormRef = useRef(null);
	const transactionTimelineRef = useRef();
	const handleNoteFormSubmit = useCallback(() => {
		transactionNoteFormRef.current?.handleSubmit?.();
	}, []);
	const handleNoteFormReset = useCallback(() => {
		transactionNoteFormRef.current?.form?.reset?.();
	}, []);
	const handleSaveSuccess = useCallback((response_0) => {
		refreshGridData();
	}, [refreshGridData]);
	const handleSaveChanges = useCallback(async () => {
		setSidesheetLoading(true);
		await formRef.current?.form?.submit();
		setSidesheetLoading(false);
	}, [setSidesheetLoading, formRef]);
	const [{ data: transactionAttachmentsData, loading: fetchTransactionAttachmentsLoading }, fetchTransactionAttachments] = useAxiosMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/search`, {
		method: "post",
		data: {
			pageSize: 50,
			filterElements: [{
				searchField: "TransactionId",
				searchValue: transaction.transactionId,
				searchOperator: "="
			}, {
				searchField: "IsDeleted",
				searchValue: 0,
				searchOperator: "="
			}]
		}
	});
	const { enqueueSnackbar } = useSnackbar();
	const getAttachments = useCallback(async () => {
		try {
			setTransactionAttachments((await fetchTransactionAttachments()).data.pageList);
			refetchTransaction();
		} catch (error) {
			console.error("Failed to fetch attachments:", error);
			if (error?.message !== "canceled") enqueueSnackbar("Attachment fetch failed: We encountered a system error. Please try again or contact support if the issue persists.", {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
		}
	}, [
		fetchTransactionAttachments,
		enqueueSnackbar,
		refetchTransaction,
		setTransactionAttachments
	]);
	const tabNames = [
		t("Details"),
		t("History"),
		t("Attachments"),
		t("Notes")
	];
	const headerItemInfo = useMemo(() => {
		const items = [{
			label: "Status",
			statusChip: {
				label: transaction.udpTransactionUdpTransactionTypeStatus?.name,
				status: transactionTypeStatusColorsMap[transaction.udpTransactionUdpTransactionTypeStatus?.name] || "default"
			}
		}];
		if (transaction?.currentRevisionNo) items.push({
			label: "Revision",
			value: `${transaction.currentRevisionNo}`
		});
		return items;
	}, [transaction, transactionTypeStatusColorsMap]);
	const handleUploadFiles = useCallback(async () => {
		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/${transaction.transactionId}/upload`, {
				method: "post",
				headers: {
					transactionId: transaction.transactionId,
					attachmentTypeId: attachmentType.transactionAttachmentTypeId
				},
				data: formData
			});
			await getAttachments();
			setCurrentAttachments([]);
			setOpenInnerSidesheetState({ 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,
		getAttachments,
		setOpenInnerSidesheetState,
		transaction.transactionId,
		setCurrentAttachments,
		setAttachmentProgress
	]);
	const innerSidesheetList = useMemo(() => [
		{
			open: openInnerSidesheetState.workflowAction,
			closeSheet: () => setOpenInnerSidesheetState({ workflowActions: false }),
			title: "Available Workflow Actions",
			children: /* @__PURE__ */ React.createElement(WorkflowActions, {
				transaction,
				closeSideSheet: () => {
					setOpenInnerSidesheetState({ workflowActions: false });
					refetchTransaction();
				},
				refreshGridData
			})
		},
		{
			open: openInnerSidesheetState.attachments,
			closeSheet: () => setOpenInnerSidesheetState({ attachments: false }),
			title: "Add Attachment",
			buttonLabel: "Save",
			buttonOneDisabled: !attachmentType || currentAttachments.length <= 0,
			onSubmit: () => {
				handleUploadFiles().then(() => refreshGridData()).catch((error_1) => console.error(error_1));
			},
			children: /* @__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
			})
		},
		{
			open: openInnerSidesheetState.notes,
			closeSheet: () => setOpenInnerSidesheetState({ notes: false }),
			title: "Add Note",
			buttonLabel: "Save note",
			buttonTwoLabel: "Clear",
			buttonTwoAction: handleNoteFormReset,
			onSubmit: handleNoteFormSubmit,
			children: /* @__PURE__ */ React.createElement(TransactionNoteForm, {
				ref: transactionNoteFormRef,
				businessObjectKey: transaction?.businessObjectKey,
				closeSideSheet: () => {
					setOpenInnerSidesheetState({ notes: false });
					setRefreshNotes(true);
				},
				noteTypes,
				fetchNoteTypesLoading
			})
		}
	], [
		openInnerSidesheetState.workflowAction,
		openInnerSidesheetState.attachments,
		openInnerSidesheetState.notes,
		transaction,
		refreshGridData,
		attachmentType,
		currentAttachments,
		transactionAttachmentTypes,
		attachmentProgress,
		transactionAttachments,
		filePreview,
		handleNoteFormReset,
		handleNoteFormSubmit,
		noteTypes,
		fetchNoteTypesLoading,
		setOpenInnerSidesheetState,
		refetchTransaction,
		handleUploadFiles,
		setAttachmentType,
		setCurrentAttachments,
		setAttachmentProgress,
		setTransactionAttachments,
		setFilePreview
	]);
	const transactionDetailPageId = useMemo(() => {
		return getUiActionRenderParameters(TransactionUiActionTypeEnums.Render_Transaction_Details_Page)?.pageId;
	}, [getUiActionRenderParameters]);
	useEffect(() => {
		(async () => {
			if (!transactionAttachmentsData) getAttachments();
		})();
	}, [transactionAttachmentsData, getAttachments]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "edit-transaction-sidesheet" }, /* @__PURE__ */ React.createElement("div", { className: `edit-transaction-sidesheet-header 'is-sticky'` }, /* @__PURE__ */ React.createElement("div", { className: "edit-transaction-sidesheet-header-title" }), /* @__PURE__ */ React.createElement("div", { className: "edit-transaction-sidesheet-header-content" }, /* @__PURE__ */ React.createElement("div", { className: "edit-transaction-sidesheet-header-items" }, headerItemInfo.map((headerItem) => {
		return /* @__PURE__ */ React.createElement(EditTransactionHeaderItem, {
			key: headerItem.label,
			label: headerItem.label,
			statusChip: headerItem.statusChip,
			value: headerItem.value
		});
	})), /* @__PURE__ */ React.createElement("div", { className: "edit-transaction-sidesheet-header-buttons" }, /* @__PURE__ */ React.createElement(FluentButton, {
		color: "primary",
		onClick: () => {
			setOpenInnerSidesheetState({ attachments: true });
		}
	}, /* @__PURE__ */ React.createElement(FluentIcon, {
		component: AddIcon,
		className: "edit-transaction-header-button-icon",
		size: "small"
	}), "Attachment"), /* @__PURE__ */ React.createElement(FluentButton, {
		color: "primary",
		onClick: () => {
			setOpenInnerSidesheetState({ notes: true });
		}
	}, /* @__PURE__ */ React.createElement(FluentIcon, {
		component: AddIcon,
		className: "edit-transaction-header-button-icon",
		size: "small"
	}), "Note")), /* @__PURE__ */ React.createElement("div", { className: "divider" }, /* @__PURE__ */ React.createElement(Divider, null)), /* @__PURE__ */ React.createElement("div", { className: "edit-transaction-sidesheet-tabs" }, /* @__PURE__ */ React.createElement(UdpTabs, {
		value: selectedTab,
		onChange: (value, tabIndex) => {
			setSelectedTab(tabIndex);
		},
		tabList: tabNames.map((tabName) => ({ label: tabName })),
		buttonWidth: "100%"
	}))), /* @__PURE__ */ React.createElement("div", { className: "divider" }, /* @__PURE__ */ React.createElement(Divider, null))), /* @__PURE__ */ React.createElement("div", { className: "edit-transaction-sidesheet-body" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(UdpTabPanel, {
		value: selectedTab,
		index: TRANSACTION_TAB.DETAILS
	}, transactionDetailPageId ? /* @__PURE__ */ React.createElement(UdpTransactionCustomPage, {
		transactionTypeId,
		transactionUiActionType: TransactionUiActionTypeEnums.Render_Transaction_Details_Page,
		formRef,
		transaction,
		refetchTransaction,
		setHasUnsavedChanges,
		refreshGridData,
		additionalPageParms,
		onSubmitSuccess: handleSaveSuccess
	}) : /* @__PURE__ */ React.createElement(DynamicTransactionDomainForm, {
		transaction,
		formRef,
		domainName,
		transactionTypeId,
		transactionUiActionType: TransactionUiActionTypeEnums.Render_Transaction_Details_Page,
		setHasUnsavedChanges,
		refetchTransaction,
		onSubmitSuccess: handleSaveSuccess,
		catalogObject
	})), /* @__PURE__ */ React.createElement(UdpTabPanel, {
		value: selectedTab,
		index: TRANSACTION_TAB.HISTORY
	}, /* @__PURE__ */ React.createElement(TransactionTimeline, {
		ref: transactionTimelineRef,
		transactionId: transaction?.transactionId
	})), /* @__PURE__ */ React.createElement(UdpTabPanel, {
		value: selectedTab,
		index: TRANSACTION_TAB.ATTACHMENTS
	}, /* @__PURE__ */ React.createElement(TransactionAttachments, {
		transactionAttachments: transactionAttachmentsData,
		isLoading: fetchTransactionAttachmentsLoading
	})), /* @__PURE__ */ React.createElement(UdpTabPanel, {
		value: selectedTab,
		index: TRANSACTION_TAB.NOTES
	}, /* @__PURE__ */ React.createElement(TransactionNotes, {
		businessObjectKey: transaction?.businessObjectKey,
		refreshNotes,
		setRefreshNotes,
		noteTypes,
		fetchNoteTypeLoading: fetchNoteTypesLoading
	})))), selectedTab == TRANSACTION_TAB.DETAILS && /* @__PURE__ */ React.createElement("div", { className: "edit-transaction-sidesheet-footer" }, /* @__PURE__ */ React.createElement(EditTransactionDetailsFooterItem, {
		transactionTypeId,
		transactionIsClosed,
		handleOnCancel: closeSideSheet,
		handleOnSaveChanges: handleSaveChanges,
		hideSaveChanges
	}))), openInnerSidesheetState && innerSidesheetList.map((item) => {
		return /* @__PURE__ */ React.createElement(SideSheet, {
			key: item.title,
			open: item.open,
			width: 600,
			title: item.title,
			onClose: item.closeSheet,
			buttonLabel: item?.buttonLabel,
			buttonOneDisabled: item?.buttonOneDisabled,
			buttonTwoLabel: item?.buttonTwoLabel,
			buttonTwoAction: item?.buttonTwoAction,
			onSubmit: item?.onSubmit,
			color: "primary"
		}, item.children);
	}));
};
//#endregion
export { EditTransaction as default };

//# sourceMappingURL=EditTransaction.mjs.map