import { ConfigService } from "../../../configService/index.mjs";
import { TransactionUiActionTypeEnums, UdpSearchEnums } from "../../../enums/unitySystemEnums.mjs";
import { useHandleAxiosSnackbar } from "../../../utilities/apiHelpers.mjs";
import { useAxiosMutate } from "../../../utilities/useAxiosMutate.mjs";
import { FluentDialog } from "../../../UI/feedback/FluentDialog.mjs";
import { LinearProgress } from "../../../UI/loading/LinearProgress.mjs";
import { SearchMethodUdpGrid } from "../../../UI/templates/newGrid/SearchMethodUdpGrid.mjs";
import { useTransactionEngine } from "../../../utilities/transactions/useTransactionEngine.mjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpTransactionsPage/UdpTransactionGrid.jsx
const UDP_TRANSACTION_GRID_ID = "32c0fd0b-bb94-497a-b47a-6c7e8f746134";
const UdpTransactionGrid = (props) => {
	const { transactionTypeId, domainName, transactionTypeLoading, handleGridApiCallback, openAddTransaction, openViewTransaction, openEditTransaction, openAttachmentTransaction, openWorkflowActionTransaction, openCreateRevision, searchMethodObject, domainColumnFormatters = {}, refreshGridData, gridApi, initialFilterModel, initialGridOptions = {}, catalogObject, gridTitle, hideCreateTransaction = false, columnDefProperties, paginationAutoPageSize, customActions = [], calendarViewEnabled = false, onShowCalendarView } = props;
	const [dialogOpen, setDialogOpen] = useState(false);
	const [selectedTransaction, setSelectedTransaction] = useState(null);
	const { t } = useTranslation();
	const { hasRevisions, transactionTypeGridColumns, transactionTypeColumnDefProperties, transactionTypePageConfiguration, getUiActionRenderParameters, transactionTypeStatusColorsMap, getTransactionTypeLabel, transactionTypeStatuses, canCancel } = useTransactionEngine(transactionTypeId);
	const columnDefinitionProperties = useMemo(() => ({
		...transactionTypeColumnDefProperties,
		...columnDefProperties
	}), [transactionTypeColumnDefProperties, columnDefProperties]);
	const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
	const [{ data, loading: cancelLoading, error: cancelError }, cancelTransaction] = useAxiosMutate(`${ConfigService.productV1ApiUrl}`, `udptransaction/${selectedTransaction?.transactionId}/cancelTransaction`, { method: "post" }, {});
	const handleDialogClose = () => {
		setSelectedTransaction(null);
		setDialogOpen(false);
	};
	const handleConfirmActionDialog = useCallback(async () => {
		try {
			if ((await cancelTransaction())?.status === 200) {
				refreshGridData();
				handleSuccessSnackbar(t(`Transaction has been cancelled successfully`));
			} else handleErrorSnackbar(new Error(t(`Error cancelling Transaction. Please try again later.`)));
		} catch (error) {
			handleErrorSnackbar(error);
		} finally {
			handleDialogClose();
		}
	}, [
		cancelTransaction,
		refreshGridData,
		handleErrorSnackbar,
		handleSuccessSnackbar,
		t
	]);
	const removeTimeFromDate = (date) => {
		const parsedDate = new Date(date);
		if (parsedDate.getTime()) {
			const year = parsedDate.getFullYear();
			const month = parsedDate.getMonth() + 1;
			const day = parsedDate.getDate().toString();
			return `${year}-${month.toString()}-${day}`;
		}
		return parsedDate;
	};
	const transactionLabel = useMemo(() => {
		return getTransactionTypeLabel(selectedTransaction) ?? selectedTransaction?.entityBusinessKey;
	}, [getTransactionTypeLabel, selectedTransaction]);
	const pdfViewPageId = useMemo(() => {
		return getUiActionRenderParameters(TransactionUiActionTypeEnums.Render_View_Pdf_Page)?.pageId;
	}, [getUiActionRenderParameters]);
	const columnDefs = useMemo(() => {
		const initialColumnDefs = [
			{
				headerName: columnDefinitionProperties?.["transactionId"]?.displayName || t("Transaction Id"),
				field: "transactionId",
				hide: true,
				order: columnDefinitionProperties?.["transactionId"]?.order || Number.MAX_SAFE_INTEGER
			},
			{
				headerName: columnDefinitionProperties?.["createdOn"]?.displayName || t("Created On"),
				field: "createdOn",
				hide: columnDefinitionProperties?.["createdOn"]?.hide,
				order: columnDefinitionProperties?.["createdOn"]?.order || Number.MAX_SAFE_INTEGER,
				cellDataType: "dateString",
				valueFormatter: (params) => {
					return removeTimeFromDate(params?.data.createdOn);
				}
			},
			{
				headerName: columnDefinitionProperties?.["currentStatusId"]?.displayName || t("Current Status"),
				field: "currentStatusId",
				hide: columnDefinitionProperties?.["currentStatusId"]?.hide,
				order: columnDefinitionProperties?.["currentStatusId"]?.order || Number.MAX_SAFE_INTEGER,
				cellRenderer: "statusRenderer",
				cellRendererParams: {
					statusMappingConfig: transactionTypeStatusColorsMap,
					getStatusValue: (params_0) => params_0?.data.udpTransactionUdpTransactionTypeStatus.name
				},
				filter: "agSetColumnFilter",
				filterParams: {
					values: (params_1) => {
						if (transactionTypeStatuses) params_1.success(transactionTypeStatuses);
					},
					keyCreator: (params_2) => params_2.value.transactionTypeStatusId,
					valueFormatter: (params_3) => params_3.value.name
				},
				valueFormatter: (params_4) => params_4?.data.udpTransactionUdpTransactionTypeStatus.name
			},
			...hasRevisions ? [{
				headerName: columnDefinitionProperties?.["currentRevisionNo"]?.displayName || t("Revision No"),
				field: "currentRevisionNo",
				hide: columnDefinitionProperties?.["currentRevisionNo"]?.hide,
				order: columnDefinitionProperties?.["currentRevisionNo"]?.order || Number.MAX_SAFE_INTEGER
			}] : [],
			{
				headerName: columnDefinitionProperties?.["lastEventTypeId"]?.displayName || t("Last Event Type"),
				field: "lastEventTypeId",
				hide: columnDefinitionProperties?.["lastEventTypeId"]?.hide,
				order: columnDefinitionProperties?.["lastEventTypeId"]?.order || Number.MAX_SAFE_INTEGER,
				valueFormatter: (params_5) => params_5?.data.udpTransactionUdpTransactionEventType.name
			},
			{
				headerName: columnDefinitionProperties?.["attachments"]?.displayName || t("Attachments"),
				field: "attachments",
				hide: columnDefinitionProperties?.["attachments"]?.hide,
				pinned: "right",
				maxWidth: 100,
				onCellClicked: (event) => {
					openAttachmentTransaction(event.data);
				},
				valueFormatter: (params_6) => {
					return params_6?.data.udpTransactionUdpTransactionAttachment.length;
				}
			},
			{
				headerName: columnDefinitionProperties?.["actions"]?.displayName || t("Actions"),
				field: "actions",
				hide: columnDefinitionProperties?.["actions"]?.hide,
				cellRenderer: "actionsRenderer",
				cellRendererParams: { actionList: [
					{
						id: 0,
						title: t("Next Steps"),
						iconName: "panel-right-expand",
						handleOnClick: (e, params_7) => {
							openWorkflowActionTransaction(params_7?.data);
						}
					},
					...pdfViewPageId ? [{
						id: 1,
						title: t("View"),
						iconName: "view",
						handleOnClick: (e_0, params_8) => {
							openViewTransaction(params_8?.data);
						},
						disabled: !pdfViewPageId
					}] : [],
					{
						id: 2,
						title: t("Edit"),
						iconName: "edit",
						handleOnClick: (e_1, params_9) => {
							openEditTransaction(params_9?.data);
						}
					},
					...hasRevisions ? [{
						id: 3,
						title: t("Create Revision"),
						iconName: "add",
						handleOnClick: (e_2, params_10) => {
							openCreateRevision(params_10?.data);
						},
						disabled: !hasRevisions
					}] : [],
					...canCancel ? [{
						id: 4,
						title: t("Cancel"),
						iconName: "close16",
						handleOnClick: (e_3, params_11) => {
							setSelectedTransaction(params_11?.data);
							setDialogOpen(true);
						}
					}] : [],
					...customActions
				] }
			}
		];
		transactionTypeGridColumns?.forEach((gridColumn) => {
			const propertyName = gridColumn?.propertyName || "";
			let valueFormatter = (params_12) => {
				return params_12?.data ? params_12?.data?.entityBusinessObject[propertyName] : "";
			};
			let onCellClicked = null;
			if (domainColumnFormatters[propertyName]) {
				valueFormatter = domainColumnFormatters[propertyName].formatter;
				onCellClicked = domainColumnFormatters[propertyName].onCellClicked || null;
			}
			let agColumnFilter = "agTextColumnFilter";
			let cellDataType = null;
			const matchingFieldInfo = catalogObject?.properties?.find((objectProperty) => {
				return objectProperty.name === propertyName;
			});
			if (matchingFieldInfo?.type.toLowerCase() == "datetime") {
				agColumnFilter = "agDateColumnFilter";
				cellDataType = "dateString";
			}
			const propertyPrefix = !!matchingFieldInfo ? `${UdpSearchEnums.UdpBusinessDomainPrefix}.` : "";
			const propertyVarPrefix = !!matchingFieldInfo ? `${UdpSearchEnums.UdpBusinessDomainPrefix}_` : "";
			initialColumnDefs.push({
				headerName: gridColumn?.displayName,
				field: `${propertyPrefix}${domainName}.${propertyName}`,
				hide: columnDefinitionProperties?.[`${propertyVarPrefix}${propertyName}`]?.hide,
				order: columnDefinitionProperties?.[`${propertyVarPrefix}${propertyName}`]?.order || Number.MAX_SAFE_INTEGER,
				valueFormatter,
				onCellClicked,
				cellRenderer: columnDefinitionProperties?.[`${propertyVarPrefix}${propertyName}`]?.cellRenderer || null,
				cellRendererParams: columnDefinitionProperties?.[`${propertyVarPrefix}${propertyName}`]?.cellRendererParams || null,
				filter: agColumnFilter,
				cellDataType
			});
		});
		Object.keys(domainColumnFormatters).forEach((columnKey) => {
			if (!(transactionTypeGridColumns?.map((col) => col.propertyName))?.includes(columnKey)) {
				let formatedHeaderName = columnKey.slice(0, 1).toUpperCase() + columnKey.slice(1);
				initialColumnDefs.push({
					headerName: formatedHeaderName,
					field: `${UdpSearchEnums.UdpBusinessDomainPrefix}.${domainName}.${columnKey}`,
					hide: columnDefinitionProperties?.[`${UdpSearchEnums.UdpBusinessDomainPrefix}_${columnKey}`]?.hide,
					order: columnDefinitionProperties?.[`${UdpSearchEnums.UdpBusinessDomainPrefix}_${columnKey}`]?.order || Number.MAX_SAFE_INTEGER,
					valueFormatter: domainColumnFormatters[columnKey].formatter,
					onCellClicked: domainColumnFormatters[columnKey].onCellClicked || null,
					cellRenderer: columnDefinitionProperties?.[`${UdpSearchEnums.UdpBusinessDomainPrefix}_${columnKey}`]?.cellRenderer || null,
					cellRendererParams: columnDefinitionProperties?.[`${UdpSearchEnums.UdpBusinessDomainPrefix}_${columnKey}`]?.cellRendererParams || null
				});
			}
		});
		if (columnDefinitionProperties) return initialColumnDefs.sort((a, b) => a.order - b.order);
		return initialColumnDefs;
	}, [
		domainName,
		t,
		openViewTransaction,
		openEditTransaction,
		openAttachmentTransaction,
		openWorkflowActionTransaction,
		domainColumnFormatters,
		transactionTypeGridColumns,
		openCreateRevision,
		hasRevisions,
		pdfViewPageId,
		transactionTypeStatusColorsMap,
		catalogObject,
		transactionTypeStatuses,
		canCancel,
		columnDefinitionProperties,
		customActions
	]);
	const headerConfig = {
		title: gridTitle || transactionTypePageConfiguration?.gridTitle || domainName,
		primaryActionButton: hideCreateTransaction || transactionTypePageConfiguration?.hideCreateTransaction ? null : {
			label: transactionTypePageConfiguration?.createTransactionButtonLabel || `${domainName} Entry`,
			iconName: "add",
			onClick: () => {
				openAddTransaction();
			}
		},
		secondaryActionButtons: calendarViewEnabled ? [{
			iconOnly: true,
			iconName: "calendar",
			label: t("Calendar View"),
			onClick: () => onShowCalendarView?.()
		}] : void 0
	};
	const gridFunctions = [
		{ name: "openSavedViews" },
		{ name: "agGridExport" },
		{ name: "agGridHideShowColumns" },
		{ name: "agGridSizeColumnsToFit" },
		{ name: "agGridAutoSizeColumns" },
		{ name: "agGridResetColumns" }
	];
	const gridOptions = useMemo(() => {
		return {
			pagination: true,
			paginationAutoPageSize: paginationAutoPageSize ?? transactionTypePageConfiguration?.paginationAutoPageSize ?? true,
			rowSelection: "none",
			...initialGridOptions
		};
	}, [
		initialGridOptions,
		paginationAutoPageSize,
		transactionTypePageConfiguration
	]);
	const searchMethodConfig = useMemo(() => {
		let combinedSearchObject = {
			eagerLoad: true,
			filterElements: [{
				searchField: "transactionTypeId",
				searchOperator: "=",
				searchValue: transactionTypeId
			}, {
				searchField: "isDeleted",
				searchOperator: "=",
				searchValue: false
			}]
		};
		if (searchMethodObject) {
			let combinedFilterElems = combinedSearchObject.filterElements.concat(searchMethodObject?.filterElements || []);
			combinedSearchObject = {
				...combinedSearchObject,
				...searchMethodObject
			};
			combinedSearchObject = {
				...combinedSearchObject,
				filterElements: combinedFilterElems
			};
		}
		return {
			requestUrl: `${ConfigService.productV1ApiUrl}/UdpTransaction/search`,
			customSearchObject: combinedSearchObject
		};
	}, [transactionTypeId, searchMethodObject]);
	useEffect(() => {
		if (gridApi && initialFilterModel && Object.keys(initialFilterModel).length) {
			gridApi.setFilterModel(initialFilterModel);
			gridApi.onFilterChanged();
		}
	}, [gridApi, initialFilterModel]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, transactionTypeLoading && /* @__PURE__ */ React.createElement(LinearProgress, null), /* @__PURE__ */ React.createElement(SearchMethodUdpGrid, {
		gridHeaderConfig: headerConfig,
		gridFunctions,
		gridOptions,
		columnDefs,
		searchMethodConfig,
		gridApiCallback: handleGridApiCallback,
		gridId: UDP_TRANSACTION_GRID_ID,
		entityName: domainName
	}), /* @__PURE__ */ React.createElement(FluentDialog, {
		title: t(`Cancel Transaction`),
		message: `Are you sure you want to cancel the transaction for ${transactionLabel || domainName}
        ?`,
		labelOne: t("Confirm"),
		actionOne: handleConfirmActionDialog,
		labelTwo: t("Cancel"),
		actionTwo: handleDialogClose,
		open: dialogOpen,
		handleClose: handleDialogClose,
		loading: cancelLoading
	}));
};
//#endregion
export { UdpTransactionGrid as default };

//# sourceMappingURL=UdpTransactionGrid.mjs.map