import { Form } from "../../utilities/form/Form.mjs";
import { Field } from "../../utilities/form/Field.mjs";
import { ConfigService } from "../../configService/index.mjs";
import { useHandleAxiosSnackbar } from "../../utilities/apiHelpers.mjs";
import { useUser } from "../../utilities/auth/useUser.mjs";
import { apiMutate } from "../../utilities/useAxiosMutate.mjs";
import { getSanitizedName } from "../../utilities/entities/entityUtilities.mjs";
import { useAxiosGet } from "../../utilities/useAxiosGet.mjs";
import { usePromotedMethodEntity } from "../../hooks/usePromotedMethodEntity.mjs";
import { executeQueryAdHoc } from "../utilities/methodUtils.mjs";
import { UdpButton } from "../../UI/fluent-web-components/UdpButton.mjs";
import { UdpAutocomplete } from "../../UI/fluent-web-components/UdpAutocomplete.mjs";
import { UdpCard } from "../../UI/fluent-web-components/UdpCard.mjs";
import { UdpFileInput } from "../../UI/fluent-web-components/UdpFileInput.mjs";
import { AmbientStepper } from "../../UI/inputs/menus/AmbientStepper/AmbientStepper.mjs";
import { UdpDivider } from "../../UI/fluent-web-components/UdpDivider.mjs";
import { UdpDropdown } from "../../UI/fluent-web-components/UdpDropdown.mjs";
import { UdpIcon } from "../../UI/fluent-web-components/UdpIcon.mjs";
import { UdpText } from "../../UI/fluent-web-components/UdpText.mjs";
import { UdpTextInput } from "../../UI/fluent-web-components/UdpTextInput.mjs";
import { handleExcelFileUpload, handleJsonFileUpload, handleTextFileUpload } from "./fileUtils.mjs";
import { FileImportConfigCard } from "./FileImportConfigCard.mjs";
import { c } from "react-compiler-runtime";
import React, { useEffect, useState } from "react";
//#region src/udp/fileImportMapping/FileImportMappingWizard.jsx
const FileImportMappingWizard = (props) => {
	const $ = c(70);
	const { refetchMappings, setNewFileMappingSidesheetOpen, verifyRequiredFields } = props;
	const user = useUser();
	const [importHeaderData, setImportHeaderData] = useState();
	const [udpObjectList, setUdpObjectList] = useState();
	const [selectedDomain, setSelectedDomain] = useState();
	const [selectedFileType, setSelectedFileType] = useState();
	const [fileObject, setFileObject] = useState();
	let t0;
	if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
		t0 = [];
		$[0] = t0;
	} else t0 = $[0];
	const [fileItems, setFileItems] = useState(t0);
	let t1;
	if ($[1] === Symbol.for("react.memo_cache_sentinel")) {
		t1 = {};
		$[1] = t1;
	} else t1 = $[1];
	const [fileImportMappingObject, setFileImportMappingObject] = useState(t1);
	const [activeStep, setActiveStep] = useState(0);
	const [showIndexNumbers, setShowIndexNumbers] = useState(false);
	const [errorText, setErrorText] = useState("");
	const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
	const executeCreateFileMapping = _temp;
	const { data: udpObjectEntity } = usePromotedMethodEntity("UdpObjectInfo", true);
	let t2;
	if ($[2] === Symbol.for("react.memo_cache_sentinel")) {
		t2 = {};
		$[2] = t2;
	} else t2 = $[2];
	const [t3] = useAxiosGet(ConfigService.productV1ApiUrl, "UdpFileImportType", t2, false);
	const { data: allowedFileTypesData } = t3;
	let t4;
	if ($[3] !== udpObjectEntity?.unityBaseSearchMethod?.apiMethodId || $[4] !== user?.id) {
		t4 = async () => {
			if (udpObjectEntity?.unityBaseSearchMethod?.apiMethodId && user?.id) {
				const sapUserRes = await executeQueryAdHoc({ data: {
					eagerLoad: true,
					pageSize: 200,
					filterElements: []
				} }, udpObjectEntity?.unityBaseSearchMethod?.apiMethodId);
				if (sapUserRes?.data?.pageList.length > 0) setUdpObjectList(sapUserRes?.data?.pageList);
			}
		};
		$[3] = udpObjectEntity?.unityBaseSearchMethod?.apiMethodId;
		$[4] = user?.id;
		$[5] = t4;
	} else t4 = $[5];
	const searchUdpObjectData = t4;
	const filterCatalogObjectList = udpObjectList;
	const getNameFormattedOptionLabel = _temp2;
	let t5;
	if ($[6] !== fileObject || $[7] !== selectedFileType.extension) {
		t5 = async (properties) => {
			let result;
			if (selectedFileType.extension === ".csv" || selectedFileType.extension === ".txt") result = await handleTextFileUpload(fileObject, properties);
			else if (selectedFileType.extension === ".xlsx") result = await handleExcelFileUpload(fileObject, properties);
			else if (selectedFileType.extension === ".json") result = await handleJsonFileUpload(fileObject, properties);
			setImportHeaderData(result?.headers);
		};
		$[6] = fileObject;
		$[7] = selectedFileType.extension;
		$[8] = t5;
	} else t5 = $[8];
	const handleFileUpload = t5;
	let t6;
	let t7;
	if ($[9] !== searchUdpObjectData) {
		t6 = () => {
			searchUdpObjectData();
		};
		t7 = [searchUdpObjectData];
		$[9] = searchUdpObjectData;
		$[10] = t6;
		$[11] = t7;
	} else {
		t6 = $[10];
		t7 = $[11];
	}
	useEffect(t6, t7);
	let t8;
	if ($[12] !== fileImportMappingObject?.mapping || $[13] !== fileImportMappingObject?.properties || $[14] !== handleErrorSnackbar || $[15] !== handleSuccessSnackbar || $[16] !== refetchMappings || $[17] !== selectedDomain?.name || $[18] !== selectedFileType.id || $[19] !== setNewFileMappingSidesheetOpen) {
		t8 = async (values) => {
			if ((await executeCreateFileMapping({
				name: values.name,
				objectInfoSanitizedName: getSanitizedName(selectedDomain?.name),
				fileImportType: selectedFileType?.id,
				mapping: JSON.stringify(fileImportMappingObject?.mapping),
				properties: JSON.stringify(fileImportMappingObject?.properties)
			}).catch((res) => {
				handleErrorSnackbar(res);
			}))?.status === 201) {
				handleSuccessSnackbar("Created Mapping");
				refetchMappings();
				setNewFileMappingSidesheetOpen(false);
			}
		};
		$[12] = fileImportMappingObject?.mapping;
		$[13] = fileImportMappingObject?.properties;
		$[14] = handleErrorSnackbar;
		$[15] = handleSuccessSnackbar;
		$[16] = refetchMappings;
		$[17] = selectedDomain?.name;
		$[18] = selectedFileType.id;
		$[19] = setNewFileMappingSidesheetOpen;
		$[20] = t8;
	} else t8 = $[20];
	const handleCreateNewFieldMapping = t8;
	let t9;
	if ($[21] !== importHeaderData || $[22] !== selectedDomain?.objectFieldInfo || $[23] !== showIndexNumbers || $[24] !== verifyRequiredFields) {
		t9 = (values_0) => {
			let valid = true;
			selectedDomain?.objectFieldInfo?.forEach((option_1) => {
				if (!option_1.dataType.endsWith("?") && !option_1.isPrimaryKey && !option_1.udpType) {
					if (!Object.entries(values_0).some((obj) => obj[1].businessObjectKey === option_1.businessObjectKey)) {
						if (verifyRequiredFields) valid = false;
					}
				}
			});
			if (!valid) {
				setErrorText("All required Udp fields must have a mapping");
				return;
			}
			const filteredMappings = Object.entries(values_0).filter(_temp3).reduce(_temp4, {});
			const mappedFieldIndexes = Object.keys(filteredMappings).map(_temp5);
			const fieldMappings = Object.values(filteredMappings).map((selectedUdpField, index) => ({
				udpField: selectedUdpField.name,
				importFileField: !showIndexNumbers ? importHeaderData[mappedFieldIndexes[index]] : null,
				headerIndex: !showIndexNumbers ? -1 : mappedFieldIndexes[index]
			}));
			setFileImportMappingObject((prev) => ({
				...prev,
				mapping: fieldMappings
			}));
			setActiveStep(_temp6);
		};
		$[21] = importHeaderData;
		$[22] = selectedDomain?.objectFieldInfo;
		$[23] = showIndexNumbers;
		$[24] = verifyRequiredFields;
		$[25] = t9;
	} else t9 = $[25];
	const handleUpdateFieldMapping = t9;
	let t10;
	if ($[26] !== handleFileUpload) {
		t10 = (values_1) => {
			setFileImportMappingObject((prev_1) => {
				const properties_0 = {};
				Object.keys(values_1).forEach((propKey) => properties_0[propKey] = "value" in values_1[propKey] ? values_1[propKey]?.value : values_1[propKey]);
				return {
					...prev_1,
					properties: properties_0
				};
			});
			if ("includesHeader" in values_1 && values_1?.includesHeader.value === false) setShowIndexNumbers(true);
			handleFileUpload(values_1);
			setActiveStep(_temp7);
		};
		$[26] = handleFileUpload;
		$[27] = t10;
	} else t10 = $[27];
	const handleUpdateFileProperties = t10;
	const getUdpFieldOptionLabel = _temp8;
	let t11;
	if ($[28] === Symbol.for("react.memo_cache_sentinel")) {
		t11 = (e) => {
			const items = e.target.value;
			setFileItems(items);
			setFileObject(items.find(_temp9)?.file);
		};
		$[28] = t11;
	} else t11 = $[28];
	const handleAddFileToUpload = t11;
	let t12;
	bb0: {
		if (selectedFileType) {
			let t13;
			if ($[29] !== selectedFileType.properties) {
				t13 = JSON.parse(selectedFileType?.properties);
				$[29] = selectedFileType.properties;
				$[30] = t13;
			} else t13 = $[30];
			t12 = t13;
			break bb0;
		}
		t12 = void 0;
	}
	const formattedFileTypeProperties = t12;
	let t13;
	if ($[31] === Symbol.for("react.memo_cache_sentinel")) {
		t13 = { marginBottom: 20 };
		$[31] = t13;
	} else t13 = $[31];
	let t14;
	if ($[32] === Symbol.for("react.memo_cache_sentinel")) {
		t14 = [
			"File",
			"Domain",
			"Field Mappings",
			"Review"
		];
		$[32] = t14;
	} else t14 = $[32];
	let t15;
	if ($[33] !== activeStep) {
		t15 = /* @__PURE__ */ React.createElement("div", { style: t13 }, /* @__PURE__ */ React.createElement(AmbientStepper, {
			activeStep,
			steps: t14,
			orientation: "vertical"
		}));
		$[33] = activeStep;
		$[34] = t15;
	} else t15 = $[34];
	let t16;
	if ($[35] !== activeStep || $[36] !== allowedFileTypesData || $[37] !== fileItems || $[38] !== fileObject || $[39] !== formattedFileTypeProperties || $[40] !== handleUpdateFileProperties || $[41] !== selectedFileType) {
		t16 = activeStep === 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(UdpDropdown, {
			name: "fileImportType",
			label: "File Type",
			onChange: (e_0) => setSelectedFileType(e_0.target.value),
			options: allowedFileTypesData || [],
			optionLabel: "name",
			optionValue: "id",
			value: selectedFileType,
			required: true
		}), selectedFileType && /* @__PURE__ */ React.createElement("div", { style: { marginTop: 5 } }, /* @__PURE__ */ React.createElement(UdpFileInput, {
			value: fileItems,
			onChange: handleAddFileToUpload,
			accept: ".csv,.txt,.xlsx,.json",
			maxFiles: 1
		})), /* @__PURE__ */ React.createElement(Form, {
			id: "fileProperties",
			onSubmit: handleUpdateFileProperties
		}, formattedFileTypeProperties?.map(_temp0), /* @__PURE__ */ React.createElement(UdpButton, {
			appearance: "secondary",
			type: "submit",
			form: "fileProperties",
			disabled: !fileObject
		}, "Next")));
		$[35] = activeStep;
		$[36] = allowedFileTypesData;
		$[37] = fileItems;
		$[38] = fileObject;
		$[39] = formattedFileTypeProperties;
		$[40] = handleUpdateFileProperties;
		$[41] = selectedFileType;
		$[42] = t16;
	} else t16 = $[42];
	let t17;
	if ($[43] !== activeStep || $[44] !== filterCatalogObjectList || $[45] !== selectedDomain) {
		t17 = activeStep === 1 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(UdpAutocomplete, {
			name: "domain",
			label: "Domain",
			onChange: (e_1) => setSelectedDomain(e_1.target.value),
			options: filterCatalogObjectList,
			optionLabel: getNameFormattedOptionLabel,
			optionValue: "id",
			value: selectedDomain,
			required: true
		}), /* @__PURE__ */ React.createElement("div", { style: {
			float: "right",
			display: "flex",
			gap: 8,
			marginTop: 8
		} }, /* @__PURE__ */ React.createElement(UdpButton, {
			onClick: () => setActiveStep(_temp1),
			disabled: activeStep === 0
		}, "Prev"), /* @__PURE__ */ React.createElement(UdpButton, {
			appearance: "secondary",
			onClick: () => setActiveStep(_temp10),
			disabled: !selectedDomain
		}, "Next")));
		$[43] = activeStep;
		$[44] = filterCatalogObjectList;
		$[45] = selectedDomain;
		$[46] = t17;
	} else t17 = $[46];
	let t18;
	if ($[47] !== activeStep || $[48] !== errorText || $[49] !== handleUpdateFieldMapping || $[50] !== importHeaderData || $[51] !== selectedDomain?.objectFieldInfo || $[52] !== showIndexNumbers) {
		t18 = activeStep === 2 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { style: {
			display: "flex",
			flexDirection: "row",
			justifyContent: "space-between",
			paddingTop: 20
		} }, /* @__PURE__ */ React.createElement(UdpText, { variant: "caption1Strong" }, showIndexNumbers ? "Column index's" : "File Headers"), /* @__PURE__ */ React.createElement(UdpText, { variant: "caption1Strong" }, "UDP Fields")), /* @__PURE__ */ React.createElement(UdpDivider, { style: { margin: "5px 0px" } }), /* @__PURE__ */ React.createElement(Form, {
			id: "fieldMappings",
			onSubmit: handleUpdateFieldMapping
		}, importHeaderData?.map((field, index_0) => /* @__PURE__ */ React.createElement("div", { key: index_0 }, /* @__PURE__ */ React.createElement("div", { style: {
			display: "flex",
			flexDirection: "row",
			alignItems: "center",
			gap: 10
		} }, /* @__PURE__ */ React.createElement(UdpText, { style: { width: "40%" } }, showIndexNumbers ? "index " + index_0 : field), /* @__PURE__ */ React.createElement(UdpIcon, {
			style: { width: "10%" },
			name: "arrow-right"
		}), /* @__PURE__ */ React.createElement("div", { style: { flex: 2 } }, /* @__PURE__ */ React.createElement(Field, {
			component: UdpDropdown,
			multiple: false,
			name: `udpFieldMapping${index_0}`,
			options: selectedDomain?.objectFieldInfo,
			optionLabel: getUdpFieldOptionLabel,
			optionValue: "businessObjectKey",
			includeErrorPadding: false,
			clearable: true
		}))), /* @__PURE__ */ React.createElement(UdpDivider, { style: { margin: "5px 0px" } }))), /* @__PURE__ */ React.createElement("div", { style: {
			paddingTop: 20,
			textAlign: "right",
			color: "red"
		} }, errorText), /* @__PURE__ */ React.createElement("div", { style: {
			display: "flex",
			justifyContent: "flex-start",
			gap: 8,
			paddingTop: 16
		} }, /* @__PURE__ */ React.createElement(UdpButton, {
			onClick: () => setActiveStep(_temp11),
			disabled: activeStep === 0
		}, "Prev"), /* @__PURE__ */ React.createElement(UdpButton, {
			appearance: "secondary",
			type: "submit",
			form: "fieldMappings"
		}, "Next"))));
		$[47] = activeStep;
		$[48] = errorText;
		$[49] = handleUpdateFieldMapping;
		$[50] = importHeaderData;
		$[51] = selectedDomain?.objectFieldInfo;
		$[52] = showIndexNumbers;
		$[53] = t18;
	} else t18 = $[53];
	let t19;
	if ($[54] !== activeStep || $[55] !== handleCreateNewFieldMapping) {
		t19 = activeStep === 3 && /* @__PURE__ */ React.createElement(Form, {
			id: "createMapping",
			onSubmit: handleCreateNewFieldMapping
		}, /* @__PURE__ */ React.createElement(Field, {
			component: UdpTextInput,
			name: "name",
			label: "Mapping Name"
		}), /* @__PURE__ */ React.createElement("div", { style: {
			display: "flex",
			justifyContent: "flex-start",
			gap: 8,
			paddingTop: 16
		} }, /* @__PURE__ */ React.createElement(UdpButton, {
			onClick: () => setActiveStep(_temp12),
			disabled: activeStep === 0
		}, "Prev"), /* @__PURE__ */ React.createElement(UdpButton, {
			appearance: "primary",
			type: "submit",
			form: "createMapping"
		}, "Create Mapping")));
		$[54] = activeStep;
		$[55] = handleCreateNewFieldMapping;
		$[56] = t19;
	} else t19 = $[56];
	let t20;
	if ($[57] !== t15 || $[58] !== t16 || $[59] !== t17 || $[60] !== t18 || $[61] !== t19) {
		t20 = /* @__PURE__ */ React.createElement(UdpCard, { width: "100%" }, t15, t16, t17, t18, t19);
		$[57] = t15;
		$[58] = t16;
		$[59] = t17;
		$[60] = t18;
		$[61] = t19;
		$[62] = t20;
	} else t20 = $[62];
	let t21;
	if ($[63] !== fileImportMappingObject?.mapping || $[64] !== fileImportMappingObject?.properties || $[65] !== selectedDomain?.name) {
		t21 = fileImportMappingObject?.mapping && /* @__PURE__ */ React.createElement("div", { style: { marginTop: 10 } }, /* @__PURE__ */ React.createElement(FileImportConfigCard, {
			fileMappingRecord: {
				mapping: fileImportMappingObject?.mapping,
				properties: fileImportMappingObject?.properties
			},
			domain: selectedDomain?.name.replace(/([A-Z])/g, " $1").trim()
		}));
		$[63] = fileImportMappingObject?.mapping;
		$[64] = fileImportMappingObject?.properties;
		$[65] = selectedDomain?.name;
		$[66] = t21;
	} else t21 = $[66];
	let t22;
	if ($[67] !== t20 || $[68] !== t21) {
		t22 = /* @__PURE__ */ React.createElement(React.Fragment, null, t20, t21);
		$[67] = t20;
		$[68] = t21;
		$[69] = t22;
	} else t22 = $[69];
	return t22;
};
async function _temp(data) {
	return apiMutate(ConfigService.productV1ApiUrl, "UdpFileImportMapping", { method: "post" }, { data });
}
function _temp2(option) {
	return option?.name.replace(/([A-Z])/g, " $1").trim();
}
function _temp3(t0) {
	const [, value] = t0;
	return value !== null;
}
function _temp4(acc, t0) {
	const [key_0, value_0] = t0;
	acc[key_0] = value_0;
	return acc;
}
function _temp5(key_1) {
	return parseInt(key_1.split("udpFieldMapping")[1], 10);
}
function _temp6(prev_0) {
	return prev_0 + 1;
}
function _temp7(prev_2) {
	return prev_2 + 1;
}
function _temp8(option_2) {
	if (!option_2.dataType.endsWith("?") && !option_2.isPrimaryKey && !option_2.udpType) return `${option_2.name.replace(/([A-Z])/g, " $1").trim()}*`;
	return `${option_2.name} - ${option_2.dataType}`;
}
function _temp9(item) {
	return item.kind === "pending";
}
function _temp0(property) {
	return property?.options ? /* @__PURE__ */ React.createElement(Field, {
		key: property.propertyName,
		component: UdpDropdown,
		multiple: false,
		name: property.propertyName,
		label: property.label,
		options: property.options,
		optionLabel: "name",
		optionValue: "value",
		required: property?.required
	}) : /* @__PURE__ */ React.createElement(Field, {
		key: property.propertyName,
		component: UdpTextInput,
		name: property.propertyName,
		label: property.label,
		required: property?.required
	});
}
function _temp1(prev_3) {
	return prev_3 - 1;
}
function _temp10(prev_4) {
	return prev_4 + 1;
}
function _temp11(prev_5) {
	return prev_5 - 1;
}
function _temp12(prev_6) {
	return prev_6 - 1;
}
//#endregion
export { FileImportMappingWizard as default };

//# sourceMappingURL=FileImportMappingWizard.mjs.map