import { Form } from "../../utilities/form/Form.mjs";
import { Field } from "../../utilities/form/Field.mjs";
import { SubmitButton } from "../../utilities/form/SubmitButton.mjs";
import { FormButtons } from "../../utilities/form/FormButtons.mjs";
import { ConfigService } from "../../configService/index.mjs";
import { useUser } from "../../utilities/auth/useUser.mjs";
import { apiMutate } from "../../utilities/useAxiosMutate.mjs";
import { FluentTextFieldAutoComplete } from "../inputs/textField/FluentTextFieldAutoComplete.mjs";
import { LayoutUnit } from "../../layout/LayoutUnit.mjs";
import { AmbientCard } from "../surfaces/cards/AmbientCard/AmbientCard.mjs";
import { LinearProgress as LinearProgress$1 } from "../loading/LinearProgress.mjs";
import { FluentTextField } from "../inputs/textField/FluentTextField.mjs";
import { DragDropFileUpload } from "../../uploader/DragDropFileUpload.mjs";
import React, { useCallback, useEffect, useState } from "react";
import { Button } from "@material-ui/core";
import { useSnackbar } from "notistack";
import { useHistory } from "react-router-dom";
import { useTranslation } from "react-i18next";
//#region src/UI/support/SupportCaseForm.jsx
const SupportCaseForm = ({ onSubmit, initialValues = {}, handleCloseSupportCaseSideSheet }) => {
	const { t } = useTranslation();
	const user = useUser();
	const { enqueueSnackbar, closeSnackbar } = useSnackbar();
	const [severityOptions, setSeverityOptions] = useState([]);
	const [environmentOptions, setEnvironmentOptions] = useState([]);
	const [brandOptions, setBrandOptions] = useState([]);
	const [uploadedFiles, setUploadedFiles] = useState([]);
	const [unityState, setUnityState] = useState();
	const [loadingState, setLoadingState] = useState(false);
	const baseUrl = ConfigService.productV1ApiUrl;
	const unityUrl = ConfigService.supportV1ApiUrl;
	const unityEnv = ConfigService.config.UNITY_ENVIRONMENT;
	const [uploadKey, setUploadKey] = useState(0);
	const [restrictedFiles, setRestrictedFiles] = useState({});
	const history = useHistory();
	const getFileRestrictions = useCallback(async () => apiMutate(baseUrl, `udpunitysupport/supportFileUploadRestrictions`, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [baseUrl, user?.currentTenantId]);
	const getFileRestrictionsUnity = useCallback(async () => apiMutate(unityUrl, `evergrncaseattachment/get-attachment-restrictions`, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [unityUrl, user?.currentTenantId]);
	const getSeverityUnity = useCallback(async () => apiMutate(unityUrl, `caseseverity/get-case-severity`, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [unityUrl, user?.currentTenantId]);
	const getEnvironmentUnity = useCallback(async () => apiMutate(unityUrl, `evergrncaseenvironment/get-case-environments`, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [unityUrl, user?.currentTenantId]);
	const getSeverity = useCallback(async () => apiMutate(baseUrl, `udpunitysupport/severities`, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [baseUrl, user?.currentTenantId]);
	const getEnvironment = useCallback(async () => apiMutate(baseUrl, `udpunitysupport/environments`, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [baseUrl, user?.currentTenantId]);
	useCallback(async () => apiMutate(baseUrl, `udpunitysupport/tenantCaseAccount/` + user?.currentTenantId, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [baseUrl, user?.currentTenantId]);
	const getTenantCaseBrand = useCallback(async () => apiMutate(ConfigService.tenantV2ApiUrl, `tenant/products`, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [user?.currentTenantId]);
	const getTenantSubscribedProducts = useCallback(async () => apiMutate(ConfigService.tenantV1ApiUrl, `tenantProducts?tenantId=${user?.currentTenantId}`, {
		method: "get",
		headers: { currentTenantId: user?.currentTenantId }
	}), [user?.currentTenantId]);
	const getCasesEnv = {
		Development: "100000003",
		Build: "100000003",
		Staging: "100000001",
		Production: "100000000"
	};
	function getCaseEnvironment() {
		return getCasesEnv[unityEnv] || "100000003";
	}
	let brandId = "416b0ca8-e679-ef11-ac20-6045bdcd3d86";
	const postCaseAttachment = useCallback((values) => {
		const data = new FormData();
		uploadedFiles.forEach((file) => {
			data.append("files", file);
		});
		data.append("EvergrnCaseName", values.title);
		data.append("EvergrnDescription", values.description);
		data.append("EvergrnCaseEnvironment", getCaseEnvironment());
		data.append("EvergrnSeverity", values.severity.value);
		const matchingProduct = brandOptions.find((product) => product.productId == ConfigService.config.UNITY_PRODUCT_ID);
		if (matchingProduct && matchingProduct.value) brandId = matchingProduct.value;
		data.append("EvergrnBrandId", brandId);
		data.append("UDPDriveUnityProductId", ConfigService.config.UNITY_PRODUCT_ID);
		return apiMutate(baseUrl, `udpunitysupport/case`, {
			method: "post",
			headers: { "Content-Type": "multipart/form-data" }
		}, { data });
	}, [
		baseUrl,
		uploadedFiles,
		getCaseEnvironment,
		brandOptions,
		brandId
	]);
	const postCaseAttachmentUnity = useCallback((values_0) => {
		const data_0 = new FormData();
		uploadedFiles.forEach((file_0) => {
			data_0.append("files", file_0);
		});
		data_0.append("EvergrnCaseName", values_0.title);
		data_0.append("EvergrnDescription", values_0.description);
		data_0.append("EvergrnCaseEnvironment", getCaseEnvironment());
		data_0.append("EvergrnSeverity", values_0.severity.value);
		data_0.append("EvergrnBrandId", values_0.product?.value || brandId);
		data_0.append("UDPDriveUnityProductId", ConfigService.config.UNITY_PRODUCT_ID);
		return apiMutate(unityUrl, `evergrncase/post-case`, {
			method: "post",
			headers: { "Content-Type": "multipart/form-data" }
		}, { data: data_0 });
	}, [
		unityUrl,
		uploadedFiles,
		getCaseEnvironment,
		brandId
	]);
	useEffect(() => {
		const fetchData = async () => {
			try {
				if (ConfigService.config.UNITY_PRODUCT_ID === "1") setUnityState(true);
				else setUnityState(false);
				let getFileRestrictionsResponse = unityState ? await getFileRestrictionsUnity() : await getFileRestrictions();
				let severityResponse = unityState ? await getSeverityUnity() : await getSeverity();
				let environmentResponse = unityState ? await getEnvironmentUnity() : await getEnvironment();
				if (getFileRestrictionsResponse) {
					const fileRestrictionsData = getFileRestrictionsResponse.data;
					setRestrictedFiles(fileRestrictionsData);
				}
				if (severityResponse) setSeverityOptions(severityResponse.data.map((item) => ({
					value: item.externalUUID.toString(),
					label: item.name
				})));
				if (environmentResponse) setEnvironmentOptions(environmentResponse.data.map((item_0) => ({
					value: item_0.evergrnCaseEnvironmentValue.toString(),
					label: item_0.evergrnCaseEnvironmentLabel
				})));
				const brandResponse = await getTenantCaseBrand();
				const tenantSubscribedProductsResponse = await getTenantSubscribedProducts();
				if (brandResponse && tenantSubscribedProductsResponse) {
					const brandArray = brandResponse.data.filter((brandItem) => brandItem.externalUuid != null);
					setBrandOptions(tenantSubscribedProductsResponse.data.map((subscribedProduct) => {
						const foundProduct = brandArray.find((brandItem_0) => brandItem_0.productId === subscribedProduct.productId);
						if (!foundProduct) return null;
						return {
							...subscribedProduct,
							value: foundProduct.externalUuid?.toString(),
							label: foundProduct.name.toString()
						};
					}).filter(Boolean));
				}
			} catch (error) {
				console.error("Error fetching data:", error);
			}
		};
		fetchData();
	}, [
		unityState,
		getSeverityUnity,
		getEnvironmentUnity,
		getFileRestrictionsUnity,
		getFileRestrictions,
		getSeverity,
		getEnvironment,
		getTenantCaseBrand,
		getTenantSubscribedProducts
	]);
	const handleUploadFile = (files) => {
		const identifiedRestrictedExtensions = [];
		const identifiedRestrictedFileSizes = [];
		files.forEach((file_1) => {
			const fileExtension = file_1.name.includes(".") ? "." + file_1.name.split(".").pop().toLowerCase() : "";
			if (restrictedFiles.restrictedExtensions.includes(fileExtension)) identifiedRestrictedExtensions.push(fileExtension);
			if (file_1.size > restrictedFiles.maxFileSize) identifiedRestrictedFileSizes.push(file_1.name);
		});
		const isAcceptableExtensions = identifiedRestrictedExtensions.length === 0;
		const isAcceptableSizes = identifiedRestrictedFileSizes.length === 0;
		if (!(isAcceptableExtensions && isAcceptableSizes)) {
			if (!isAcceptableExtensions) enqueueSnackbar(t(`Restricted file type(s). ${[...new Set(identifiedRestrictedExtensions)].join(", ")}`), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
			if (!isAcceptableSizes) enqueueSnackbar(t(`File(s) are too large (5MB limit). ${identifiedRestrictedFileSizes.join(", ")}`), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
			setUploadKey((prevKey) => prevKey + 1);
			return;
		}
		setUploadedFiles(files);
	};
	const handleSubmit = async (values_1) => {
		setLoadingState(true);
		let response;
		try {
			response = unityState ? await postCaseAttachmentUnity(values_1) : await postCaseAttachment(values_1);
		} catch (apiError) {
			console.error("post Case API call failed:", apiError);
			enqueueSnackbar(t("Submission failed"), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				},
				action: (key) => /* @__PURE__ */ React.createElement(Button, {
					color: "primary",
					size: "small",
					id: "udpRecord-SupportCaseForm-close",
					onClick: () => {
						closeSnackbar(key);
					}
				}, "close")
			});
			setLoadingState(false);
			return { submitError: apiError.message };
		}
		if (!response?.data?.evergrnCaseId) {
			console.error("API call succeeded but no case ID returned");
			enqueueSnackbar(t("Submission failed - No case ID returned"), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				},
				action: (key_0) => /* @__PURE__ */ React.createElement(Button, {
					color: "primary",
					size: "small",
					id: "udpRecord-SupportCaseForm-close",
					onClick: () => {
						closeSnackbar(key_0);
					}
				}, "close")
			});
			setLoadingState(false);
			return { submitError: "No case ID was returned from the server" };
		}
		window.dispatchEvent(new CustomEvent("support-case-created"));
		try {
			handleCloseSupportCaseSideSheet();
		} catch (closeError) {
			console.error("Error closing sheet:", closeError);
		}
		enqueueSnackbar(t(`Support Case Created. View your cases`), {
			variant: "success",
			anchorOrigin: {
				vertical: "top",
				horizontal: "center"
			},
			action: (key_1) => /* @__PURE__ */ React.createElement(Button, {
				color: "primary",
				size: "small",
				id: "udpRecord-SupportCaseForm-here",
				onClick: () => {
					try {
						const caseId = response.data.evergrnCaseId;
						let url;
						if (unityState) {
							url = `/support/cases/${caseId}`;
							history.push(url);
						} else {
							url = `${ConfigService.config.UNITY_URL}/support/cases/${caseId}`;
							window.location.href = url;
						}
						closeSnackbar(key_1);
					} catch (navError) {
						console.error("Navigation error:", navError);
						closeSnackbar(key_1);
					}
				}
			}, "here")
		});
		try {
			await onSubmit(values_1);
		} catch (onSubmitError) {
			console.error("Error in onSubmit:", onSubmitError);
		}
		setLoadingState(false);
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, loadingState && /* @__PURE__ */ React.createElement(LinearProgress$1, null), /* @__PURE__ */ React.createElement(Form, { onSubmit: handleSubmit }, /* @__PURE__ */ React.createElement(AmbientCard, { fullWidth: true }, /* @__PURE__ */ React.createElement(Field, {
		component: FluentTextField,
		name: "title",
		label: t("Title"),
		placeholder: t("Enter a brief title for your issue"),
		variant: "outlined",
		fullWidth: true,
		autoFocus: true,
		required: true
	}), unityState && /* @__PURE__ */ React.createElement(Field, {
		component: FluentTextFieldAutoComplete,
		name: "product",
		label: t("Product"),
		variant: "outlined",
		margin: "normal",
		size: "small",
		options: brandOptions,
		optionKey: "label",
		style: { width: "100%" },
		disableClearable: true,
		id: "udpRecord-CreateSupportCaseForm-product",
		udprecordid: "udpRecord-CreateSupportCaseForm-product"
	}), /* @__PURE__ */ React.createElement(Field, {
		component: FluentTextFieldAutoComplete,
		name: "severity",
		label: t("Severity"),
		variant: "outlined",
		margin: "normal",
		size: "small",
		options: severityOptions,
		optionKey: "label",
		style: { width: "100%" },
		disableClearable: true,
		id: "udpRecord-CreateSupportCaseForm-severity",
		udprecordid: "udpRecord-CreateSupportCaseForm-severity",
		required: true
	})), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "xxs" }), /* @__PURE__ */ React.createElement(AmbientCard, { fullWidth: true }, /* @__PURE__ */ React.createElement(Field, {
		name: "description",
		component: FluentTextField,
		multiline: true,
		rows: 10,
		minRows: 3,
		maxRows: 20,
		required: true,
		label: "Description",
		placeholder: "Please describe your issue in detail"
	})), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "xxs" }), /* @__PURE__ */ React.createElement(AmbientCard, { fullWidth: true }, /* @__PURE__ */ React.createElement(DragDropFileUpload, {
		key: uploadKey,
		title: "Attachments",
		multiple: true,
		minHeight: "100px",
		maxHeight: "400px",
		acceptedFiles: ".pdf,.doc,.docx,.png,.jpg,.jpeg",
		handleUploadFile
	})), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "xxs" }), /* @__PURE__ */ React.createElement(FormButtons, null, /* @__PURE__ */ React.createElement(SubmitButton, {
		color: "primary",
		variant: "contained",
		disablePristine: false
	}, "Submit Ticket"))));
};
//#endregion
export { SupportCaseForm as default };

//# sourceMappingURL=SupportCaseForm.mjs.map