import { ConfigService } from "../../../../configService/index.mjs";
import { apiMutate } from "../../../../utilities/useAxiosMutate.mjs";
import { useAxiosGet } from "../../../../utilities/useAxiosGet.mjs";
import { LinearProgress as LinearProgress$1 } from "../../../../UI/loading/LinearProgress.mjs";
import { Divider as Divider$1 } from "../../../../UI/utilityDisplay/Divider.mjs";
import { AmbientAlert } from "../../../../UI/feedback/AmbientAlert.mjs";
import { EmptyStateDisplay } from "../../../../UI/dataDisplay/EmptyStateDisplay.mjs";
import { FileViewer } from "../../../../UI/fileViewer/FileViewer.mjs";
import AttachmentTransactionAttachmentList from "../components/AttachmentTransactionAttachmentList.mjs";
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { makeStyles } from "@material-ui/core";
import { ViewIcon } from "@fluentui/react-icons";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpTransactionsPage/sidesheets/AttachmentTransaction.jsx
const AttachmentTransaction = (props) => {
	const { transaction, attachmentRef } = props;
	const [selectedAttachment, setSelectedAttachment] = useState("");
	const attachments = transaction?.udpTransactionUdpTransactionAttachment || [];
	const { t } = useTranslation();
	const [{ data: attachmentFileInfo }, refetchattachmentFileInfo] = useAxiosGet(`${ConfigService.productV1ApiUrl}`, `UdpTransactionAttachment/${selectedAttachment?.transactionAttachmentId}/udpDriveFile/download`, {}, true);
	const [{ data: attachmentFile, loading: loadingFile, error: downloadError }, refetchAttachmentFile] = useAxiosGet(`${ConfigService.productV1ApiUrl}`, `UdpTransactionAttachment/${selectedAttachment?.transactionAttachmentId}/download`, { responseType: "blob" }, true);
	const blobUrl = useMemo(() => {
		if (!attachmentFile) return null;
		const pdfBlob = new Blob([attachmentFile], { type: "application/pdf" });
		return URL.createObjectURL(pdfBlob);
	}, [attachmentFile]);
	useEffect(() => {
		if (selectedAttachment) {
			refetchattachmentFileInfo();
			refetchAttachmentFile();
		}
	}, [
		selectedAttachment,
		refetchattachmentFileInfo,
		refetchAttachmentFile
	]);
	const getErrorMessage = () => {
		if (!downloadError) return null;
		const status = downloadError.response?.status;
		if (status === 404) return t("The requested attachment could not be found.");
		if (status >= 500) return t("A server error occured. Please try again later.");
		return downloadError.message || t("An unexpected error occured.");
	};
	let fileDataObj = {
		filePath: blobUrl,
		fileExtension: attachmentFileInfo?.extension
	};
	const fixedHeight = "calc(100vh - 140px)";
	const classStyles = makeStyles((theme) => ({
		sidesheet: {
			display: "flex",
			flexDirection: "row",
			flex: 1,
			height: fixedHeight
		},
		attachmentListContainer: {
			textAlign: "left",
			width: "35%",
			height: fixedHeight
		},
		attachmentListHeader: {
			backgroundColor: "white",
			justifyItems: "left",
			paddingLeft: "5%"
		},
		attachmentListHeaderPrimaryText: {
			fontSize: "var(--h6-font-size)",
			fontWeight: "var(--body1-font-weight)",
			color: "var(--text-main)"
		},
		attachmentListHeaderSecondaryText: {
			fontSize: "var(--body2-font-size)",
			color: "var(--text-secondary)",
			paddingBottom: "2%"
		},
		attachemntFileInfoCol: {
			width: "50%",
			display: "flex",
			flexDirection: "column",
			flex: 1,
			overflowY: "auto",
			height: "calc(100vh - 50px)"
		},
		attachmentFileNameHeader: { backgroundColor: "white" },
		attachmentFileName: {
			color: "var(--text-main)",
			fontSize: "var(--h6-font-size)",
			fontWeight: "var(--body1-font-weight)",
			marginTop: "1%",
			marginBottom: "1%",
			justifySelf: "center"
		},
		fileViewer: {
			marginLeft: "var(--spacing-02)",
			marginRight: "var(--spacing-02)"
		},
		divider: { "& MuiDivider-root": { backgroundColor: "var(--gray-02)" } }
	}))();
	useImperativeHandle(attachmentRef, () => ({ downloadSelectedFile: async () => {
		if (!selectedAttachment) return;
		try {
			const url = (await apiMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/${selectedAttachment.transactionAttachmentId}/udpDriveFile/download`, {})).data.link;
			const link = document.createElement("a");
			link.href = url;
			link.download = selectedAttachment.fileName ?? selectedAttachment.name;
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		} catch (e) {
			console.error("Download failed", e);
		}
	} }));
	const handleOpenInNewTab = useCallback((e_0) => {
		e_0?.preventDefault();
		if (blobUrl) window.open(blobUrl, "_blank");
	}, [blobUrl]);
	const refetchAttachment = () => {
		refetchattachmentFileInfo();
		refetchAttachmentFile();
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: classStyles.sidesheet }, /* @__PURE__ */ React.createElement("div", { className: classStyles.attachmentListContainer }, /* @__PURE__ */ React.createElement("div", { className: classStyles.attachmentListHeader }, /* @__PURE__ */ React.createElement("div", { className: classStyles.attachmentListHeaderPrimaryText }, "Attachments"), /* @__PURE__ */ React.createElement("div", { className: classStyles.attachmentListHeaderSecondaryText }, attachments?.length + " file(s) attached")), /* @__PURE__ */ React.createElement("div", { className: classStyles.divider }, /* @__PURE__ */ React.createElement(Divider$1, null)), /* @__PURE__ */ React.createElement(AttachmentTransactionAttachmentList, {
		transaction,
		attachments,
		setSelectedAttachment
	})), /* @__PURE__ */ React.createElement("div", { className: classStyles.attachemntFileInfoCol }, /* @__PURE__ */ React.createElement("div", { className: classStyles.attachmentFileNameHeader }, selectedAttachment && /* @__PURE__ */ React.createElement("p", { className: classStyles.attachmentFileName }, selectedAttachment.attachmentName), /* @__PURE__ */ React.createElement("div", { className: classStyles.divider }, /* @__PURE__ */ React.createElement(Divider$1, null))), downloadError && /* @__PURE__ */ React.createElement(AmbientAlert, {
		showAlert: !!downloadError,
		alertSeverity: "error",
		alertTitle: t("Failed to load preview"),
		alertMessage: getErrorMessage(),
		alertAction: true,
		alertActionButton: t("Retry"),
		alertHandleAction: () => refetchAttachment()
	}), loadingFile && !downloadError ? /* @__PURE__ */ React.createElement(LinearProgress$1, null) : selectedAttachment && attachmentFileInfo && blobUrl ? /* @__PURE__ */ React.createElement("div", { className: classStyles.fileViewer }, /* @__PURE__ */ React.createElement(FileViewer, {
		data: attachmentFileInfo?.extension == "pdf" ? fileDataObj : [fileDataObj],
		onClickDownload: handleOpenInNewTab
	})) : !selectedAttachment && /* @__PURE__ */ React.createElement(EmptyStateDisplay, {
		icon: ViewIcon,
		primaryText: "Select an attachment to preview",
		secondaryText: "Choose a file from the attachments list to view its contents"
	}))));
};
//#endregion
export { AttachmentTransaction as default };

//# sourceMappingURL=AttachmentTransaction.mjs.map