import { ConfigService } from "../../../../../configService/index.mjs";
import { apiMutate, useAxiosMutate } from "../../../../../utilities/useAxiosMutate.mjs";
import { useCatalogStore } from "../../../../../stores/catalogStore.mjs";
import { SideSheet } from "../../../../../UI/surfaces/SideSheet.mjs";
import { AmbientCard } from "../../../../../UI/surfaces/cards/AmbientCard/AmbientCard.mjs";
import { HttpStatusCode } from "../../../../../enums/httpStatusCodesEnums.mjs";
import { EmptyStateDisplay } from "../../../../../UI/dataDisplay/EmptyStateDisplay.mjs";
import { UdpTimeline } from "../../../../../UI/timeline/UdpTimeline.mjs";
import { formatDate } from "../../../../../UI/widgets/utils/dateUtils.mjs";
import { TransactionTimelineItem } from "./TransactionTimelineItem.mjs";
import { TransactionChangeLog } from "./TransactionChangeLog.mjs";
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { LinearProgress } from "@material-ui/core";
import { useSnackbar } from "notistack";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpTransactionsPage/components/transactionHistory/TransactionTimeline.jsx
const META_DATA_BLOCKLIST = new Set([
	"businessobjectkey",
	"id",
	"ignoringloggingtransactions"
]);
const TransactionTimeline = forwardRef((props, ref) => {
	const { transactionId } = props;
	const { t } = useTranslation();
	const { enqueueSnackbar } = useSnackbar();
	const { currentApiCatalogId } = useCatalogStore();
	const [udpDomainObjects, setUdpDomainObjects] = useState(null);
	const [sideSheetOpen, setSideSheetOpen] = useState(false);
	const searchObj = useMemo(() => {
		return {
			eagerLoad: true,
			pageNumber: 0,
			pageSize: 100,
			filterElements: [{
				searchField: "transactionId",
				searchValue: transactionId,
				searchOperator: "="
			}],
			orderElements: [{
				sortColumn: "createdOn",
				sortDirection: "desc"
			}],
			getAll: true
		};
	}, [transactionId]);
	const [{ data: transactionHistory, loading: isLoading }, fetchTransactionHistory] = useAxiosMutate(ConfigService.productV1ApiUrl, `UdpTransactionHistory/search`, {
		method: "post",
		data: searchObj
	});
	const filterData = (dataObj, allowedKeys) => {
		if (!dataObj) return {};
		const allowedSet = new Set(allowedKeys.map((key) => key.toLowerCase()).filter((key_0) => !META_DATA_BLOCKLIST.has(key_0)));
		return Object.fromEntries(Object.entries(dataObj).filter(([key_1]) => allowedSet.has(key_1.toLowerCase())));
	};
	const handleOnClick = useCallback(async (transactionHistoryRecord) => {
		const domain = transactionHistoryRecord?.udpTransactionHistoryUdpAuditEvent?.domain;
		try {
			const [catalogRes, comparisonRes] = await Promise.all([apiMutate(ConfigService.integrationV2ApiUrl, `apiCatalog/${currentApiCatalogId}/catalogObject/${domain}`, { method: "get" }), apiMutate(ConfigService.productV1ApiUrl, `UdpTransactionHistory/GetComparison`, {
				method: "post",
				data: {
					auditEventId: transactionHistoryRecord.auditEventId,
					entityBusinessKey: transactionHistoryRecord.entityBusinessKey,
					transactionEventTypeId: transactionHistoryRecord.transactionEventTypeId
				}
			})]);
			const catalog = catalogRes?.data;
			if (!catalog) {
				console.error("Missing catalog metadata for domain:", domain);
				enqueueSnackbar(t("Unable to load metadata for this record."), {
					variant: "error",
					autoHideDuration: 7e3,
					anchorOrigin: {
						vertical: "top",
						horizontal: "center"
					},
					preventDuplicate: true
				});
				return;
			}
			const permissableFieldTypes = new Set([
				"string",
				"DateTime",
				"string uuid",
				"int",
				"bool"
			]);
			const catalogPropertyNames = catalog.properties.filter((field) => permissableFieldTypes.has(field.type)).map((property) => property.name);
			const data = comparisonRes.data;
			setUdpDomainObjects({
				previous: filterData(data.previous, catalogPropertyNames),
				current: filterData(data.current, catalogPropertyNames)
			});
			setSideSheetOpen(true);
		} catch (error) {
			console.error("Fetch Failed:", error);
			let userMessage = "Unable to load comparison. Please try again.";
			if (error.response && error.response.status) switch (error.response.status) {
				case HttpStatusCode.BAD_REQUEST:
					userMessage = "Data mismatch detected. Please refresh the page and try again.";
					break;
				case HttpStatusCode.NOT_FOUND:
					userMessage = "This history record no longer exists.";
					break;
				case HttpStatusCode.INTERNAL_SERVER_ERROR:
					userMessage = "System error. Please contact support if this persists.";
					break;
			}
			else if (error.request) userMessage = "Network error. Please check your connection.";
			enqueueSnackbar(t(userMessage), {
				variant: "error",
				autoHideDuration: 7e3,
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				},
				preventDuplicate: true
			});
		}
	}, [
		currentApiCatalogId,
		t,
		enqueueSnackbar
	]);
	const handleOnSideSheetClose = useCallback(() => {
		setSideSheetOpen(false);
	}, []);
	useImperativeHandle(ref, () => ({ refresh: () => {
		fetchTransactionHistory();
	} }));
	useEffect(() => {
		fetchTransactionHistory();
	}, [fetchTransactionHistory]);
	return /* @__PURE__ */ React.createElement("div", null, isLoading ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(LinearProgress, null)) : transactionHistory?.pageList?.length > 0 ? /* @__PURE__ */ React.createElement(AmbientCard, null, /* @__PURE__ */ React.createElement(UdpTimeline, null, transactionHistory?.pageList?.map((item, index) => /* @__PURE__ */ React.createElement(TransactionTimelineItem, {
		key: index,
		item,
		title: item?.udpTransactionHistoryUdpTransactionTypeTransactionAction?.name ?? item?.udpTransactionHistoryUdpTransactionEventType?.name,
		description: item?.changedByName ? `By ${item?.changedByName}` : null,
		date: item?.createdOn ? formatDate(item?.createdOn, "dd/mm/yyyy") : null,
		status: item?.udpTransactionHistoryUdpTransactionTypeStatus?.name,
		onClick: handleOnClick
	})))) : /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(EmptyStateDisplay, { primaryText: t("No History") })), udpDomainObjects && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SideSheet, {
		title: t("Domain Comparison"),
		width: 700,
		open: sideSheetOpen,
		onClose: handleOnSideSheetClose,
		PaperProps: { style: { maxWidth: "100vw" } }
	}, /* @__PURE__ */ React.createElement(TransactionChangeLog, {
		oldData: udpDomainObjects.previous,
		newData: udpDomainObjects.current
	}))));
});
TransactionTimeline.displayName = "TransactionTimeline";
//#endregion
export { TransactionTimeline as default };

//# sourceMappingURL=TransactionTimeline.mjs.map