import { Form } from "../../../../utilities/form/Form.mjs";
import { Field } from "../../../../utilities/form/Field.mjs";
import { FluentButton } from "../../../../UI/inputs/buttons/FluentButton.mjs";
import { arrayMutators } from "../../../../utilities/form/arrayMutators.mjs";
import { UdpSearchEnums } from "../../../../enums/unitySystemEnums.mjs";
import { LayoutUnit } from "../../../../layout/LayoutUnit.mjs";
import { FluentTextField } from "../../../../UI/inputs/textField/FluentTextField.mjs";
import { AmbientAutoComplete } from "../../../../UI/inputs/textField/AmbientAutoComplete.mjs";
import UdpTransactionTypePageConfigurationSidesheet from "../sidesheets/UdpTransactionTypePageConfigurationSidesheet.mjs";
import UdpTransactionTypeCalendarViewConfigurationSidesheet from "../sidesheets/UdpTransactionTypeCalendarViewConfigurationSidesheet.mjs";
import { DISABLE_ORDERING_FOR_FIELDS, REQUIRED_COLUMN_DEF_FIELDS, REQUIRED_COLUMN_DEF_MAPPING } from "../UdpTransactionTypesPage.mjs";
import { c } from "react-compiler-runtime";
import React, { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { FormControlLabel, Switch, makeStyles } from "@material-ui/core";
import { StatusCircleErrorXIcon } from "@fluentui/react-icons";
import { useTranslation } from "react-i18next";
import { FieldArray } from "react-final-form-arrays";
//#region src/udp/pages/UdpTransactionTypesPage/forms/UdpTransactionTypeForm.jsx
const useStyles = makeStyles((theme) => ({
	domainFields: {
		display: "flex",
		flexDirection: "row",
		alignItems: "flex-end",
		justifyContent: "flex-start",
		"& > *": { marginRight: theme.spacing(2) }
	},
	domainValueField: { minWidth: "150px" },
	addRemoveButtons: {
		display: "flex",
		flexDirection: "row",
		alignItems: "center",
		justifyContent: "flex-start",
		margin: `${theme.spacing(2)}px  0  0 ${-theme.spacing(2)}px`,
		"& > *": { margin: `0 ${theme.spacing(2)}px` }
	},
	deleteActionSlot: {
		width: theme.spacing(3.5),
		display: "flex",
		justifyContent: "center",
		flexShrink: 0
	},
	switchColumn: {
		display: "flex",
		flexDirection: "column",
		alignItems: "center",
		width: theme.spacing(6),
		flexShrink: 0
	},
	removeIcon: {
		fontSize: theme.spacing(3.5),
		cursor: "pointer",
		color: theme.palette.text.secondary,
		"&:hover": { color: theme.palette.error.main }
	}
}));
const buildRequiredColumnDefFields = () => REQUIRED_COLUMN_DEF_FIELDS.map((key) => [key, {
	displayName: REQUIRED_COLUMN_DEF_MAPPING[key]?.displayName || key,
	order: 0,
	hide: false
}]);
/**
* Checks for the UDP prefix, strips it if present, and returns the result.
* @param {string} value - The string to process.
* @returns {string} The shortened string or the original if no prefix found.
*/
const stripUdpPrefix = (value) => {
	if (typeof value !== "string") return value;
	if (value.startsWith(UdpSearchEnums.UdpBusinessDomainPrefix)) return value.slice(UdpSearchEnums.UdpBusinessDomainPrefix.length + 1);
	return value;
};
const computeInitialValues = (initialData, domainNameOptions, domainFieldOptions, selectedDomainName) => {
	let formattedData;
	const requiredFields = buildRequiredColumnDefFields();
	if (!initialData) return { domainFields: requiredFields };
	let domainFieldsDatasource = initialData?.pageConfiguration?.columnDefProperties ? initialData?.pageConfiguration?.columnDefProperties : initialData?.domainFields;
	const existingDomainFields = selectedDomainName === initialData?.domainName && domainFieldsDatasource ? Object.entries(domainFieldsDatasource).map(([fieldKey, fieldConfig]) => {
		return [stripUdpPrefix(fieldKey), { ...fieldConfig && typeof fieldConfig === "object" ? fieldConfig : { value: fieldConfig } }];
	}) : [[]];
	const existingKeys = existingDomainFields.map((field) => field[0]);
	const missingTransactionFields = REQUIRED_COLUMN_DEF_FIELDS.filter((key) => !existingKeys.includes(key)).map((key) => [key, {
		displayName: REQUIRED_COLUMN_DEF_MAPPING[key]?.displayName || key,
		order: 0,
		hide: false
	}]);
	formattedData = {
		...initialData,
		domainName: domainNameOptions?.find((domainName) => domainName === selectedDomainName || ""),
		domainFieldType: domainFieldOptions?.find((domainField) => domainField === initialData?.domainFieldType),
		domainFieldLabel: domainFieldOptions?.find((domainField) => domainField === initialData?.domainFieldLabel) || initialData?.domainFieldLabel,
		revisionField: domainFieldOptions?.find((domainField) => domainField === initialData?.revisionField),
		domainFields: [...missingTransactionFields, ...existingDomainFields]
	};
	return formattedData;
};
const UdpTransactionTypeForm = (props, ref) => {
	const $ = c(34);
	const { onSubmit, initialData, disableSubTypeFields, domainNameOptions, onSelectDomainName, domainFieldOptions, dateDomainFieldOptions, selectedDomainName, isPageConfigOpen, setIsPageConfigOpen, isCalendarViewConfigOpen, setIsCalendarViewConfigOpen } = props;
	const handleSubmitRef = useRef();
	const { t } = useTranslation();
	const classes = useStyles();
	let t0;
	if ($[0] !== domainFieldOptions || $[1] !== domainNameOptions || $[2] !== initialData || $[3] !== selectedDomainName) {
		t0 = () => computeInitialValues(initialData, domainNameOptions, domainFieldOptions, selectedDomainName);
		$[0] = domainFieldOptions;
		$[1] = domainNameOptions;
		$[2] = initialData;
		$[3] = selectedDomainName;
		$[4] = t0;
	} else t0 = $[4];
	const [formInitialValues] = useState(t0);
	let t1;
	if ($[5] === Symbol.for("react.memo_cache_sentinel")) {
		t1 = () => ({ submit: () => {
			handleSubmitRef?.current();
		} });
		$[5] = t1;
	} else t1 = $[5];
	useImperativeHandle(ref, t1);
	let t2;
	if ($[6] !== initialData || $[7] !== onSubmit) {
		t2 = (formData) => {
			onSubmit(formData, initialData);
		};
		$[6] = initialData;
		$[7] = onSubmit;
		$[8] = t2;
	} else t2 = $[8];
	const handleSubmit = t2;
	let t3;
	if ($[9] === Symbol.for("react.memo_cache_sentinel")) {
		t3 = { ...arrayMutators };
		$[9] = t3;
	} else t3 = $[9];
	let t4;
	if ($[10] !== formInitialValues) {
		t4 = { ...formInitialValues };
		$[10] = formInitialValues;
		$[11] = t4;
	} else t4 = $[11];
	let t5;
	if ($[12] !== classes.addRemoveButtons || $[13] !== classes.deleteActionSlot || $[14] !== classes.domainFields || $[15] !== classes.domainValueField || $[16] !== classes.removeIcon || $[17] !== classes.switchColumn || $[18] !== dateDomainFieldOptions || $[19] !== disableSubTypeFields || $[20] !== domainFieldOptions || $[21] !== domainNameOptions || $[22] !== initialData || $[23] !== isCalendarViewConfigOpen || $[24] !== isPageConfigOpen || $[25] !== onSelectDomainName || $[26] !== setIsCalendarViewConfigOpen || $[27] !== setIsPageConfigOpen || $[28] !== t) {
		t5 = (t6) => {
			const { handleSubmit: handleSubmit_0, form } = t6;
			handleSubmitRef.current = handleSubmit_0;
			const push = form?.mutators?.push ?? _temp;
			const handleDomainNameChange = (value) => {
				const nextDomainName = value || "";
				if ((form.getState().values?.domainName || "") !== nextDomainName) {
					onSelectDomainName?.(nextDomainName);
					form.change("domainFields", [...buildRequiredColumnDefFields()]);
				}
			};
			const handleDomainFieldTypeChange = (value_0) => {
				if (!value_0) form.change("domainFieldValue", "");
			};
			const hasRevision = !!form.getState().values?.hasRevision;
			const hasDomainFieldType = !!form.getState().values?.domainFieldType;
			const parseHasRevision = (value_1) => {
				const nextValue = value_1?.target ? !!value_1.target.checked : !!value_1;
				if (!nextValue) form.change("revisionField", null);
				return nextValue;
			};
			const isCalendarViewEnabled = !!form.getState().values?.calendarViewEnabled;
			const handleCalendarViewEnabledChange = (event) => {
				if (!event.target.checked) {
					form.change("isDefaultView", false);
					form.change("defaultCalendarViewType", "");
					form.change("domainStartDateProperty", "");
					form.change("domainEndDateProperty", "");
					form.change("domainPropertyToDisplay", "");
				}
			};
			return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Field, {
				component: FluentTextField,
				label: t("Name"),
				id: "name",
				name: "name",
				fullWidth: true,
				variant: "outlined",
				margin: "normal",
				size: "small",
				required: true
			}), /* @__PURE__ */ React.createElement(Field, {
				component: AmbientAutoComplete,
				label: t("Domain"),
				id: "domainName",
				name: "domainName",
				variant: "outlined",
				isMultiple: false,
				disableCloseOnSelect: false,
				options: domainNameOptions || [],
				getOptionLabelFunction: _temp2,
				additionalOnChangeAction: handleDomainNameChange
			}), /* @__PURE__ */ React.createElement(Field, {
				component: AmbientAutoComplete,
				label: "Sub-Type",
				id: "domainFieldType",
				name: "domainFieldType",
				variant: "outlined",
				isMultiple: false,
				disableCloseOnSelect: false,
				options: domainFieldOptions || [],
				getOptionLabelFunction: _temp3,
				additionalOnChangeAction: handleDomainFieldTypeChange,
				disabled: disableSubTypeFields
			}), hasDomainFieldType && /* @__PURE__ */ React.createElement(Field, {
				component: FluentTextField,
				label: t("Sub-Type Value"),
				id: "domainFieldValue",
				name: "domainFieldValue",
				fullWidth: true,
				variant: "outlined",
				margin: "normal",
				size: "small",
				disabled: disableSubTypeFields
			}), /* @__PURE__ */ React.createElement(Field, {
				component: AmbientAutoComplete,
				label: t("Field Label"),
				id: "domainFieldLabel",
				name: "domainFieldLabel",
				variant: "outlined",
				isMultiple: false,
				disableCloseOnSelect: false,
				options: domainFieldOptions || [],
				getOptionLabelFunction: _temp4,
				helperText: t("Field property to be used in transaction page labels"),
				freeSolo: true
			}), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement(FormControlLabel, {
				control: /* @__PURE__ */ React.createElement(Field, {
					component: Switch,
					id: "archiveOnCancel",
					name: "archiveOnCancel",
					type: "checkbox"
				}),
				label: t("Archive on Cancel")
			}), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement(FormControlLabel, {
				control: /* @__PURE__ */ React.createElement(Field, {
					component: Switch,
					id: "enabled",
					name: "enabled",
					type: "checkbox"
				}),
				label: t("Enabled")
			}), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement(FormControlLabel, {
				control: /* @__PURE__ */ React.createElement(Field, {
					component: Switch,
					id: "hasRevision",
					name: "hasRevision",
					type: "checkbox",
					parse: parseHasRevision
				}),
				label: t("Allow Revisions")
			}), hasRevision && /* @__PURE__ */ React.createElement(Field, {
				component: AmbientAutoComplete,
				label: "Revision Field",
				id: "revisionField",
				name: "revisionField",
				variant: "outlined",
				isMultiple: false,
				disableCloseOnSelect: false,
				options: domainFieldOptions || [],
				getOptionLabelFunction: _temp5
			}), /* @__PURE__ */ React.createElement("div", { className: classes.addRemoveButtons }, /* @__PURE__ */ React.createElement(FluentButton, {
				variant: "contained",
				color: "primary",
				onClick: () => setIsPageConfigOpen(true)
			}, t("Additional Configuration")), /* @__PURE__ */ React.createElement(FluentButton, {
				variant: "contained",
				color: "primary",
				onClick: () => setIsCalendarViewConfigOpen(true)
			}, t("Calendar View Configuration"))), /* @__PURE__ */ React.createElement(UdpTransactionTypePageConfigurationSidesheet, {
				initialData,
				isSidesheetOpen: isPageConfigOpen,
				setIsSidesheetOpen: setIsPageConfigOpen
			}), /* @__PURE__ */ React.createElement(UdpTransactionTypeCalendarViewConfigurationSidesheet, {
				initialData,
				isSidesheetOpen: isCalendarViewConfigOpen,
				setIsSidesheetOpen: setIsCalendarViewConfigOpen,
				domainFieldOptions,
				dateDomainFieldOptions,
				isCalendarViewEnabled,
				handleCalendarViewEnabledChange
			}), /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: classes.addRemoveButtons }, /* @__PURE__ */ React.createElement(FluentButton, {
				variant: "contained",
				color: "primary",
				onClick: () => push("domainFields", void 0)
			}, t("Add a Domain Field"))), /* @__PURE__ */ React.createElement(FieldArray, { name: "domainFields" }, (t7) => {
				const { fields } = t7;
				return fields.map((name, index) => {
					const fieldKey = fields?.value?.[index]?.[0];
					const isRequired = REQUIRED_COLUMN_DEF_FIELDS.includes(fieldKey);
					const disableOrderField = DISABLE_ORDERING_FOR_FIELDS.includes(fieldKey);
					return /* @__PURE__ */ React.createElement("div", {
						key: `${name}${index}`,
						className: classes.domainFields
					}, /* @__PURE__ */ React.createElement(Field, {
						component: AmbientAutoComplete,
						label: index === 0 && t("Field"),
						name: `${name}[0]`,
						variant: "outlined",
						disabled: isRequired,
						options: domainFieldOptions || [],
						freeSolo: true
					}), /* @__PURE__ */ React.createElement(Field, {
						component: FluentTextField,
						label: index === 0 && t("Display Name"),
						name: `${name}[1].displayName`,
						fullWidth: true,
						variant: "outlined",
						margin: "normal",
						size: "small",
						onChange: _temp6,
						className: classes.domainValueField
					}), /* @__PURE__ */ React.createElement(Field, {
						component: FluentTextField,
						label: index === 0 && t("Order"),
						name: `${name}[1].order`,
						fullWidth: true,
						variant: "outlined",
						margin: "normal",
						size: "small",
						type: "number",
						onChange: _temp7,
						disabled: disableOrderField,
						className: classes.domainValueField
					}), /* @__PURE__ */ React.createElement("div", { className: classes.switchColumn }, index === 0 && /* @__PURE__ */ React.createElement("span", { style: {
						fontSize: "14px",
						color: "rgba(0, 0, 0, 0.6)",
						marginBottom: "-2px",
						fontWeight: 400
					} }, t("Hide")), /* @__PURE__ */ React.createElement(Field, {
						component: Switch,
						name: `${name}[1].hide`,
						type: "checkbox"
					})), /* @__PURE__ */ React.createElement("div", { className: classes.deleteActionSlot }, !isRequired && /* @__PURE__ */ React.createElement("span", {
						onClick: () => fields.remove(index),
						className: classes.removeIcon
					}, /* @__PURE__ */ React.createElement(StatusCircleErrorXIcon, null))));
				});
			})));
		};
		$[12] = classes.addRemoveButtons;
		$[13] = classes.deleteActionSlot;
		$[14] = classes.domainFields;
		$[15] = classes.domainValueField;
		$[16] = classes.removeIcon;
		$[17] = classes.switchColumn;
		$[18] = dateDomainFieldOptions;
		$[19] = disableSubTypeFields;
		$[20] = domainFieldOptions;
		$[21] = domainNameOptions;
		$[22] = initialData;
		$[23] = isCalendarViewConfigOpen;
		$[24] = isPageConfigOpen;
		$[25] = onSelectDomainName;
		$[26] = setIsCalendarViewConfigOpen;
		$[27] = setIsPageConfigOpen;
		$[28] = t;
		$[29] = t5;
	} else t5 = $[29];
	let t6;
	if ($[30] !== handleSubmit || $[31] !== t4 || $[32] !== t5) {
		t6 = /* @__PURE__ */ React.createElement(Form, {
			onSubmit: handleSubmit,
			mutators: t3,
			initialValues: t4,
			render: t5
		});
		$[30] = handleSubmit;
		$[31] = t4;
		$[32] = t5;
		$[33] = t6;
	} else t6 = $[33];
	return t6;
};
var UdpTransactionTypeForm_default = forwardRef(UdpTransactionTypeForm);
function _temp() {}
function _temp2(option) {
	return option;
}
function _temp3(option_0) {
	return option_0;
}
function _temp4(option_1) {
	return option_1;
}
function _temp5(option_2) {
	return option_2;
}
function _temp6() {}
function _temp7() {}
//#endregion
export { UdpTransactionTypeForm_default as default };

//# sourceMappingURL=UdpTransactionTypeForm.mjs.map