import { FluentButton } from "../../../../../UI/inputs/buttons/FluentButton.mjs";
import { ConfigService } from "../../../../../configService/index.mjs";
import { useHandleAxiosSnackbar } from "../../../../../utilities/apiHelpers.mjs";
import { apiMutate, useAxiosMutate } from "../../../../../utilities/useAxiosMutate.mjs";
import { LayoutUnit } from "../../../../../layout/LayoutUnit.mjs";
import { SideSheet } from "../../../../../UI/surfaces/SideSheet.mjs";
import { LinearProgress as LinearProgress$1 } from "../../../../../UI/loading/LinearProgress.mjs";
import { FluentTextField } from "../../../../../UI/inputs/textField/FluentTextField.mjs";
import { EmptyStateDisplay } from "../../../../../UI/dataDisplay/EmptyStateDisplay.mjs";
import { PDFViewer } from "../../../../../UI/fileViewer/pdfViewer/PDFViewer.mjs";
import { ClientSideUdpGrid } from "../../../../../UI/templates/newGrid/ClientSideUdpGrid.mjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Typography } from "@material-ui/core";
import { ErrorIcon } from "@fluentui/react-icons";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpTransactionsPage/components/transactionAttachment/TransactionAttachmentPdfStitcher.jsx
const ALLOWED_EXTENSIONS = [
	"pdf",
	"jpg",
	"jpeg",
	"png",
	"gif",
	"bmp",
	"tif",
	"tiff"
];
const TransactionAttachmentPdfStitcher = (props) => {
	const { transactionAttachments = [], onDownload, onPreview, onCancel, stitchLoading, orderedRows, onSelectionChanged, onRowOrderChanged, stitchedFileName, onFileNameChange, fileNameError, tableHeight = "calc(100vh - 700px)", hidePreviewButton = false, hideDownloadButton = false, defaultPreviewSideSheet = true, transactionTypeId, transactionAttachmentTypes, disableFileName = false, onActionClick, actionButtonLabel = "", disableActionButton = false } = props;
	const { t } = useTranslation();
	const [orderedSelection, setOrderedSelection] = useState(orderedRows || []);
	const [sourceGridApi, setSourceGridApi] = useState(null);
	const [orderGridApi, setOrderGridApi] = useState(null);
	const [previewPdfOpen, setPreviewPdfOpen] = useState(false);
	const [previewPdfLoading, setPreviewPdfLoading] = useState(false);
	const [previewPdfError, setPreviewPdfError] = useState(null);
	const [previewPdfBlob, setPreviewPdfBlob] = useState(null);
	const [downloadingPdf, setDownloadingPdf] = useState(false);
	const { handleErrorSnackbar } = useHandleAxiosSnackbar();
	const [{ data: fetchedTransactionAttachmentTypes }, fetchTransactionAttachmentTypes] = useAxiosMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachmentType/search`, {
		method: "post",
		data: {
			pageSize: 50,
			filterElements: [{
				searchField: "TransactionTypeId",
				searchValue: transactionTypeId,
				searchOperator: "="
			}],
			getAll: true
		}
	});
	const resolvedTransactionAttachmentTypes = transactionAttachmentTypes ?? fetchedTransactionAttachmentTypes?.pageList;
	const executeGetStitchedPdf = useCallback(async () => {
		return await apiMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/stitchAttachmentsIntoPdf`, {
			method: "POST",
			data: {
				fileName: stitchedFileName,
				transactionAttachments: orderedSelection
			},
			responseType: "blob"
		}).catch(async (error) => {
			let errorMessage = "";
			if (error.response && error.response.data instanceof Blob) errorMessage = await error.response.data.text();
			else errorMessage = error.message;
			handleErrorSnackbar(error, t(`Failed to generate PDF ${errorMessage ? `: ${errorMessage}` : ""}`));
			setPreviewPdfError(errorMessage);
		});
	}, [
		stitchedFileName,
		orderedSelection,
		handleErrorSnackbar,
		t
	]);
	const handleOnPreviewPdfClose = useCallback(() => {
		setPreviewPdfOpen(false);
		setPreviewPdfBlob(null);
		setPreviewPdfError(null);
	}, []);
	const handleRowOrderChanged = useCallback((newOrder) => {
		if (onRowOrderChanged) onRowOrderChanged(newOrder);
		if (onSelectionChanged) onSelectionChanged(newOrder);
		setOrderedSelection(newOrder);
	}, [onRowOrderChanged, onSelectionChanged]);
	const handleSelectionChanged = useCallback((selected) => {
		setOrderedSelection((prevOrdered) => {
			const selectedIds = new Set(selected.map((item) => item.transactionAttachmentId || item.id));
			const nextOrdered = prevOrdered.filter((item_0) => selectedIds.has(item_0.transactionAttachmentId || item_0.id));
			const prevIds = new Set(prevOrdered.map((item_1) => item_1.transactionAttachmentId || item_1.id));
			const newItems = selected.filter((item_2) => !prevIds.has(item_2.transactionAttachmentId || item_2.id));
			const finalSelection = [...nextOrdered, ...newItems];
			if (onSelectionChanged) onSelectionChanged(finalSelection);
			return finalSelection;
		});
	}, [onSelectionChanged]);
	const filteredAttachments = useMemo(() => {
		return transactionAttachments.filter((item_3) => {
			const ext = item_3.extension ? item_3.extension.toLowerCase().replace(".", "") : "";
			return ALLOWED_EXTENSIONS.includes(ext);
		});
	}, [transactionAttachments]);
	const handleGridApiCallback = useCallback((api) => {
		setSourceGridApi(api);
	}, []);
	const handleOrderGridApiCallback = useCallback((api_0) => {
		setOrderGridApi(api_0);
	}, []);
	const getColumnDefs = useCallback((type) => {
		return [{
			field: "fileName",
			headerName: t("File Name"),
			tooltipField: "fileName",
			sortable: false,
			rowDrag: type === "select" ? false : true
		}, ...(transactionTypeId || transactionAttachmentTypes) && type === "select" ? [{
			headerName: t("Type"),
			field: "transactionAttachmentTypeId",
			filter: "agSetColumnFilter",
			filterParams: {
				values: (params) => {
					const values = resolvedTransactionAttachmentTypes?.map((taType) => taType.transactionAttachmentTypeId) || [];
					params.success(values);
				},
				valueFormatter: (params_0) => {
					const type_0 = resolvedTransactionAttachmentTypes?.find((taType_0) => taType_0.transactionAttachmentTypeId === params_0.value);
					return type_0 ? type_0.name : params_0.value;
				}
			},
			valueFormatter: (params_1) => {
				const type_1 = resolvedTransactionAttachmentTypes?.find((taType_1) => taType_1.transactionAttachmentTypeId === params_1?.data?.transactionAttachmentTypeId);
				return type_1 ? type_1.name : params_1?.data?.transactionAttachmentTypeId;
			}
		}] : []];
	}, [
		t,
		resolvedTransactionAttachmentTypes,
		transactionTypeId,
		transactionAttachmentTypes
	]);
	const selectAttachmentsGridOptions = useMemo(() => ({
		rowDragManaged: true,
		animateRows: true,
		suppressMoveWhenRowDragging: false,
		getRowId: (params_2) => params_2.data.transactionAttachmentId?.toString() || params_2.data.id?.toString(),
		onSelectionChanged: (event) => {
			handleSelectionChanged(event.api.getSelectedRows());
		},
		rowSelection: { mode: "multiRow" }
	}), [handleSelectionChanged]);
	const documentOrderGridOptions = useMemo(() => ({
		rowDragManaged: true,
		animateRows: true,
		suppressMoveWhenRowDragging: false,
		getRowId: (params_3) => params_3.data.transactionAttachmentId?.toString() || params_3.data.id?.toString(),
		onRowDragEnd: (event_0) => {
			const newOrder_0 = [];
			event_0.api.forEachNode((node) => {
				newOrder_0.push(node.data);
			});
			handleRowOrderChanged(newOrder_0);
		},
		onSelectionChanged: (event_1) => {
			handleSelectionChanged(event_1.api.getSelectedRows());
		},
		headerHeight: 0
	}), [handleRowOrderChanged, handleSelectionChanged]);
	const handleDownload = useCallback(async () => {
		setDownloadingPdf(true);
		try {
			const response = onDownload ? await onDownload(orderedSelection) : await executeGetStitchedPdf();
			if (response) {
				const blob = response.data;
				const url = URL.createObjectURL(blob);
				const a = document.createElement("a");
				a.href = url;
				a.download = `${stitchedFileName.trim().toLowerCase().endsWith(".pdf") ? stitchedFileName : `${stitchedFileName || "merged_files"}.pdf`}`;
				a.click();
				URL.revokeObjectURL(url);
			}
		} finally {
			setDownloadingPdf(false);
		}
	}, [
		onDownload,
		orderedSelection,
		stitchedFileName,
		executeGetStitchedPdf
	]);
	const handlePreview = useCallback(async () => {
		if (onPreview && !defaultPreviewSideSheet) return await onPreview(orderedSelection);
		setPreviewPdfOpen(true);
		setPreviewPdfLoading(true);
		try {
			const blob = (await (onPreview ? onPreview(orderedSelection) : executeGetStitchedPdf()))?.data;
			if (blob instanceof Blob) setPreviewPdfBlob(blob);
		} finally {
			setPreviewPdfLoading(false);
		}
	}, [
		onPreview,
		orderedSelection,
		executeGetStitchedPdf,
		defaultPreviewSideSheet
	]);
	useEffect(() => {
		if (!transactionAttachmentTypes && transactionTypeId) fetchTransactionAttachmentTypes().catch(() => {});
	}, [
		transactionAttachmentTypes,
		fetchTransactionAttachmentTypes,
		transactionTypeId
	]);
	useEffect(() => {
		if (sourceGridApi) {
			const selectionIds = new Set(orderedSelection.map((item_4) => item_4.transactionAttachmentId || item_4.id));
			sourceGridApi.forEachNode((node_0) => {
				const isActuallySelected = selectionIds.has(node_0.data.transactionAttachmentId || node_0.data.id);
				if (node_0.isSelected() !== isActuallySelected) node_0.setSelected(isActuallySelected, false, true);
			});
		}
	}, [sourceGridApi, orderedSelection]);
	return /* @__PURE__ */ React.createElement("div", { style: { height: "100%" } }, (stitchLoading || downloadingPdf) && /* @__PURE__ */ React.createElement(LinearProgress$1, null), /* @__PURE__ */ React.createElement("div", { style: { paddingBottom: 8 } }, /* @__PURE__ */ React.createElement(FluentTextField, {
		label: t("File Name"),
		value: stitchedFileName,
		onChange: onFileNameChange,
		error: !!fileNameError,
		helperText: fileNameError,
		fullWidth: true,
		variant: "outlined",
		disabled: disableFileName
	})), /* @__PURE__ */ React.createElement(Typography, null, t("Select Attachments (Optional)")), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement(ClientSideUdpGrid, {
		columnDefs: getColumnDefs("select"),
		rowData: filteredAttachments || [],
		gridOptions: selectAttachmentsGridOptions,
		gridApiCallback: handleGridApiCallback,
		gridHeight: tableHeight
	}), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement(Typography, null, t("Document Order")), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement(ClientSideUdpGrid, {
		columnDefs: getColumnDefs("order"),
		rowData: orderedSelection,
		gridOptions: documentOrderGridOptions,
		gridApiCallback: handleOrderGridApiCallback,
		gridHeight: tableHeight
	}), /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		justifyContent: "flex-start",
		paddingTop: "8px"
	} }, hidePreviewButton ? null : /* @__PURE__ */ React.createElement(FluentButton, {
		color: "primary",
		disabled: !orderedSelection?.length,
		onClick: handlePreview
	}, t("Preview")), hideDownloadButton ? null : /* @__PURE__ */ React.createElement(FluentButton, {
		color: "primary",
		disabled: !orderedSelection?.length || downloadingPdf,
		onClick: handleDownload
	}, t("Download")), onActionClick && /* @__PURE__ */ React.createElement(FluentButton, {
		color: "primary",
		disabled: disableActionButton,
		onClick: onActionClick
	}, t(actionButtonLabel || "Perform Action"))), /* @__PURE__ */ React.createElement(SideSheet, {
		open: previewPdfOpen,
		title: t("PDF Preview"),
		onClose: handleOnPreviewPdfClose,
		width: 660,
		progress: previewPdfLoading,
		variant: "indeterminate",
		color: "primary"
	}, previewPdfError ? /* @__PURE__ */ React.createElement(EmptyStateDisplay, {
		icon: ErrorIcon,
		primaryText: "Error loading PDF preview",
		secondaryText: previewPdfError || t("An error occurred while generating the PDF preview.")
	}) : /* @__PURE__ */ React.createElement(PDFViewer, {
		blobPDF: previewPdfBlob,
		closePDF: handleOnPreviewPdfClose,
		onClickDownload: handleDownload
	})));
};
//#endregion
export { TransactionAttachmentPdfStitcher };

//# sourceMappingURL=TransactionAttachmentPdfStitcher.mjs.map