import { ConfigService } from "../configService/index.mjs";
import { useHandleAxiosSnackbar } from "../utilities/apiHelpers.mjs";
import { apiMutate } from "../utilities/useAxiosMutate.mjs";
import { FluentIconButton } from "../UI/inputs/buttons/FluentIconButton.mjs";
import { AmbientCard } from "../UI/surfaces/cards/AmbientCard/AmbientCard.mjs";
import { FluentDialog } from "../UI/feedback/FluentDialog.mjs";
import { LinearProgress as LinearProgress$1 } from "../UI/loading/LinearProgress.mjs";
import { Box as Box$1 } from "../UI/Box.mjs";
import { AmbientAutoComplete } from "../UI/inputs/textField/AmbientAutoComplete.mjs";
import { DragDropFileUpload } from "./DragDropFileUpload.mjs";
import { AttachmentAction } from "./enums/systemEnums.mjs";
import React, { useCallback, useState } from "react";
import { Divider, IconButton, List, ListItem } from "@material-ui/core";
import { ChromeCloseIcon, DownloadIcon } from "@fluentui/react-icons";
import { useTranslation } from "react-i18next";
import DeleteIcon$1 from "@material-ui/icons/Delete";
import "./Attachments.css";
//#region src/uploader/Attachments.jsx
const removeDuplicateFiles = (incomingFiles, existingFiles) => {
	const uniqueFiles = [];
	const duplicateFiles = [];
	incomingFiles.forEach((newFile) => {
		if (existingFiles.some((existingFile) => existingFile.name === newFile.name || existingFile.fileName === newFile.name)) duplicateFiles.push(newFile);
		else uniqueFiles.push(newFile);
	});
	return {
		uniqueFiles,
		duplicateFiles
	};
};
const Attachments = ({ allowedExtensions, MAX_FILE_SIZE_MB, filePreview, setFilePreview, currentAttachments, setCurrentAttachments, attachmentTypes, attachmentType, setAttachmentType, attachmentProgress, setAttachmentProgress, previousAttachments, setPreviousAttachments }) => {
	const [attachmentDialogOpen, setAttachmentDialogOpen] = useState(false);
	const [attachmentToDelete, setAttachmentToDelete] = useState(null);
	const [attachmentToDeleteIndex, setAttachmentToDeleteIndex] = useState(0);
	const [attachmentAction, setAttachmentAction] = useState(AttachmentAction.None);
	const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
	const { t } = useTranslation();
	const initiateAttachmentAction = useCallback((action, file, index) => {
		setAttachmentAction(action);
		setAttachmentToDelete(file);
		setAttachmentToDeleteIndex(index);
		setAttachmentDialogOpen(true);
	}, []);
	const handleAttachmentDeleteClick = useCallback((file_0, index_0) => {
		initiateAttachmentAction(AttachmentAction.Delete, file_0, index_0);
	}, [initiateAttachmentAction]);
	const handleAttachmentRemoveClick = useCallback((file_1, index_1) => {
		initiateAttachmentAction(AttachmentAction.Remove, file_1, index_1);
	}, [initiateAttachmentAction]);
	const handleCloseAttachmentDialog = useCallback(() => {
		setAttachmentAction(AttachmentAction.None);
		setAttachmentToDelete({});
		setAttachmentDialogOpen(false);
	}, []);
	const removeAttachmentFromList = useCallback((attachments, setAttachments) => {
		setAttachments((prev) => prev.filter((item, i) => i !== attachmentToDeleteIndex));
		handleSuccessSnackbar(t("Attachment Removed Successfully"));
		handleCloseAttachmentDialog();
	}, [
		attachmentToDeleteIndex,
		handleSuccessSnackbar,
		handleCloseAttachmentDialog,
		t
	]);
	const deleteAttachment = useCallback(async () => {
		try {
			setAttachmentProgress(true);
			const filePayload = {
				...attachmentToDelete,
				isDeleted: true
			};
			await apiMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/${attachmentToDelete.transactionAttachmentId}`, {
				method: "put",
				data: filePayload
			});
			removeAttachmentFromList(previousAttachments, setPreviousAttachments);
		} catch (error) {
			handleErrorSnackbar("Failed to delete attachment", "We encountered a system error while trying to delete the file. Please try again.");
			console.error(error);
		} finally {
			setAttachmentProgress(false);
			setAttachmentDialogOpen(false);
		}
	}, [
		attachmentToDelete,
		removeAttachmentFromList,
		previousAttachments,
		setPreviousAttachments,
		setAttachmentProgress,
		handleErrorSnackbar
	]);
	const handleDownloadFile = useCallback(async (file_2) => {
		try {
			const url = (await apiMutate(ConfigService.productV1ApiUrl, `UdpTransactionAttachment/${file_2.transactionAttachmentId}/udpDriveFile/download`, {})).data.link;
			const link = document.createElement("a");
			link.href = url;
			link.download = file_2.fileName ?? file_2.name;
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		} catch (e) {
			console.error("Download failed", e);
		}
	}, []);
	const handleAddFiles = useCallback(async (files) => {
		const incomingFiles = Array.from(files);
		const validFiles = [];
		const invalidFiles = [];
		incomingFiles.forEach((file_3) => {
			const ext = file_3.name.split(".").pop().toLowerCase();
			const sizeInMB = file_3.size / (1024 * 1024);
			if (!allowedExtensions.includes(ext)) invalidFiles.push(`${file_3.name} (Invalid file type)`);
			else if (sizeInMB > MAX_FILE_SIZE_MB) invalidFiles.push(`${file_3.name} (Exceeds ${MAX_FILE_SIZE_MB} MB)`);
			else validFiles.push(file_3);
		});
		const { uniqueFiles, duplicateFiles } = removeDuplicateFiles(validFiles, [...previousAttachments, ...currentAttachments]);
		if (uniqueFiles.length > 0) setCurrentAttachments((prev_0) => [...prev_0, ...uniqueFiles]);
		if (invalidFiles.length > 0) {
			handleErrorSnackbar("Files not added", `The following files had errors:\n${invalidFiles.join("\n")}`);
			setFilePreview(true);
		}
		if (duplicateFiles.length > 0) handleErrorSnackbar("Duplicates skipped", `The following files already exist and were not added: ${duplicateFiles.map((f) => f.name).join(", ")}`);
	}, [
		allowedExtensions,
		MAX_FILE_SIZE_MB,
		previousAttachments,
		currentAttachments,
		setCurrentAttachments,
		handleErrorSnackbar,
		setFilePreview
	]);
	const handleAttachmentTypeSelect = useCallback((attachmentType_0) => {
		setAttachmentType(attachmentType_0);
	}, [setAttachmentType]);
	const renderCurrentAttachments = () => {
		return currentAttachments.map((file_4, index_2) => /* @__PURE__ */ React.createElement(React.Fragment, { key: index_2 }, index_2 > 0 && /* @__PURE__ */ React.createElement(Divider, { component: "li" }), /* @__PURE__ */ React.createElement(ListItem, {
			className: "list-separator-item",
			style: {
				display: "flex",
				justifyContent: "space-between"
			}
		}, /* @__PURE__ */ React.createElement(Box$1, null, file_4.fileName ? file_4.fileName : file_4.name), /* @__PURE__ */ React.createElement(Box$1, null, /* @__PURE__ */ React.createElement(IconButton, { onClick: () => handleAttachmentRemoveClick(file_4, index_2) }, /* @__PURE__ */ React.createElement(DeleteIcon$1, null))))));
	};
	const renderPreviousAttachments = () => {
		return previousAttachments.map((file_5, index_3) => /* @__PURE__ */ React.createElement(ListItem, {
			key: index_3,
			style: {
				display: "flex",
				justifyContent: "space-between"
			}
		}, /* @__PURE__ */ React.createElement(Box$1, null, file_5.fileName ?? file_5.name), /* @__PURE__ */ React.createElement(Box$1, null, /* @__PURE__ */ React.createElement(IconButton, { onClick: () => handleAttachmentDeleteClick(file_5, index_3) }, /* @__PURE__ */ React.createElement(DeleteIcon$1, null)), /* @__PURE__ */ React.createElement(IconButton, { onClick: () => handleDownloadFile(file_5) }, /* @__PURE__ */ React.createElement(DownloadIcon, null)))));
	};
	const renderConfirmationContent = () => {
		const isDeleteAction = attachmentAction === AttachmentAction.Delete;
		const actionVerb = isDeleteAction ? "delete" : "remove";
		const fileName = attachmentToDelete?.fileName ?? attachmentToDelete?.name;
		return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "deleteSubTitle" }, "Are you sure you want to ", actionVerb, " this attachment -", " ", /* @__PURE__ */ React.createElement("strong", null, `"${fileName}"`), "?"), isDeleteAction && /* @__PURE__ */ React.createElement("p", null, "This action cannot be undone."));
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "card-wrapper" }, attachmentProgress && /* @__PURE__ */ React.createElement("div", { className: "linear-progress" }, /* @__PURE__ */ React.createElement(LinearProgress$1, null)), /* @__PURE__ */ React.createElement(AmbientCard, {
		fullWidth: true,
		title: t("Add New Attachments"),
		variant: "secondary",
		subtitle: "These files will be included with the submittal(s)"
	}, /* @__PURE__ */ React.createElement(DragDropFileUpload, {
		title: "Drag and drop files here or click to browse",
		handleUploadFile: handleAddFiles,
		hideSelectFileButton: false,
		hideFilePreview: !filePreview,
		minHeight: "200px",
		maxHeight: "400px",
		multiple: true
	}), /* @__PURE__ */ React.createElement(AmbientAutoComplete, {
		variant: "outlined",
		isMultiple: false,
		value: attachmentType,
		getOptionLabelFunction: (option) => option.name,
		onChange: handleAttachmentTypeSelect,
		options: attachmentTypes?.pageList,
		label: t("Select Attachment Type"),
		required: true
	})), currentAttachments?.length > 0 && /* @__PURE__ */ React.createElement(AmbientCard, {
		fullWidth: true,
		title: t("Current Attachments"),
		subtitle: `${currentAttachments.length} file(s) attached`
	}, /* @__PURE__ */ React.createElement(List, null, renderCurrentAttachments())), previousAttachments.length > 0 && /* @__PURE__ */ React.createElement(AmbientCard, {
		fullWidth: true,
		title: t("Previous Attachments")
	}, /* @__PURE__ */ React.createElement(List, null, renderPreviousAttachments()))), /* @__PURE__ */ React.createElement(FluentDialog, {
		title: /* @__PURE__ */ React.createElement("div", { className: "deleteTitle" }, /* @__PURE__ */ React.createElement("span", null, attachmentAction === AttachmentAction.Delete ? t("Delete Attachment") : t("Remove Attachment")), /* @__PURE__ */ React.createElement(FluentIconButton, {
			"aria-label": "close",
			icon: ChromeCloseIcon,
			onClick: handleCloseAttachmentDialog
		})),
		message: renderConfirmationContent(),
		labelOne: attachmentAction === AttachmentAction.Delete ? t("Delete") : t("Remove"),
		actionOne: attachmentAction === AttachmentAction.Delete ? deleteAttachment : () => removeAttachmentFromList(currentAttachments, setCurrentAttachments),
		labelTwo: t("Cancel"),
		actionTwo: handleCloseAttachmentDialog,
		open: attachmentDialogOpen,
		handleClose: handleCloseAttachmentDialog,
		fullWidth: true
	}));
};
//#endregion
export { Attachments };

//# sourceMappingURL=Attachments.mjs.map