import { c } from "react-compiler-runtime";
import React, { useCallback, useEffect, useState } from "react";
import { Popper, TextField, makeStyles } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";
import clsx from "clsx";
//#region src/UI/inputs/textField/FluentTextFieldAutoComplete.jsx
const useStyles = makeStyles((theme) => ({
	formTextInput: { fontSize: 14 },
	labelRoot: { fontSize: 14 }
}));
const AutoCompletePopper = (props) => {
	const $ = c(2);
	let t0;
	if ($[0] !== props) {
		t0 = /* @__PURE__ */ React.createElement(Popper, {
			...props,
			placement: "bottom-start"
		});
		$[0] = props;
		$[1] = t0;
	} else t0 = $[1];
	return t0;
};
const FluentTextFieldAutoComplete = (props) => {
	const { label, placeholder, options, textFieldProps, disabled, onChange: onChangeProp, value, optionKey, additionalOnChangeAction, classes: classProps, variant = "outlined", inputProps, inputPropClasses, customPopper, disableClearable = false, defaultValue, additionalOptionKey, isMultiple = false, limitTags, renderTags, optionLabelDisplayFunction = (option) => option, groupBy = null, size = "medium", id, udprecordid, freeSolo = false, formatUserInputValue, filterOptions: filterOptionsProp, ...other } = props;
	const classes = useStyles();
	const { autocompleteRoot } = classProps || {};
	const [inputValue, setInputValue] = useState("");
	const shouldControlInputValue = freeSolo;
	const autoCompleteId = id;
	const getOptionLabel = useCallback((option_0) => {
		if (!option_0) return "";
		if (optionKey && typeof option_0 === "object") return `${optionLabelDisplayFunction(option_0[optionKey])}${additionalOptionKey ? ` - (${option_0[additionalOptionKey]})` : ""}`;
		return optionLabelDisplayFunction(option_0) || "";
	}, [
		optionKey,
		additionalOptionKey,
		optionLabelDisplayFunction
	]);
	const formatRawInput = useCallback((raw) => formatUserInputValue ? formatUserInputValue(raw) : raw, [formatUserInputValue]);
	const getComparableLabel = useCallback((option_1) => {
		if (!option_1) return "";
		if (typeof option_1 === "string") return option_1;
		return getOptionLabel(option_1);
	}, [getOptionLabel]);
	const normalizeFilterValue = useCallback((value_0) => `${value_0 ?? ""}`.toLowerCase().trim(), []);
	const defaultFilterOptions = useCallback((optionList) => {
		const input = normalizeFilterValue(inputValue);
		if (!input) return optionList;
		return optionList.filter((option_2) => normalizeFilterValue(getComparableLabel(option_2)).includes(input));
	}, [
		getComparableLabel,
		normalizeFilterValue,
		inputValue
	]);
	const hasMatchingValue = useCallback((values, candidate) => {
		if (!Array.isArray(values) || candidate === null || candidate === void 0) return false;
		const candidateLabel = getComparableLabel(candidate);
		return values.some((item) => {
			if (item === candidate) return true;
			if (optionKey && typeof item === "object" && typeof candidate === "object") {
				const itemKey = item?.[optionKey];
				const candidateKey = candidate?.[optionKey];
				if (itemKey !== void 0 && candidateKey !== void 0) return itemKey === candidateKey;
			}
			if (optionKey && typeof item === "object" && typeof candidate === "string") {
				const itemKey_0 = item?.[optionKey];
				if (itemKey_0 !== void 0) return `${itemKey_0}` === candidate;
			}
			if (optionKey && typeof candidate === "object" && typeof item === "string") {
				const candidateKey_0 = candidate?.[optionKey];
				if (candidateKey_0 !== void 0) return `${candidateKey_0}` === item;
			}
			return getComparableLabel(item) === candidateLabel;
		});
	}, [optionKey, getComparableLabel]);
	const commitFreeSoloMultiple = useCallback(() => {
		if (!freeSolo || !isMultiple) return false;
		const raw_0 = (inputValue || "").trim();
		if (!raw_0) return false;
		const formatted = formatRawInput(raw_0);
		if (formatted === "" || formatted === null || formatted === void 0) {
			setInputValue("");
			return false;
		}
		const currentValues = Array.isArray(value) ? value : [];
		if (hasMatchingValue(currentValues, formatted)) {
			setInputValue("");
			return false;
		}
		const nextValues = [...currentValues, formatted];
		if (additionalOnChangeAction) additionalOnChangeAction(nextValues);
		onChangeProp?.(nextValues);
		setInputValue("");
		return true;
	}, [
		freeSolo,
		isMultiple,
		inputValue,
		formatRawInput,
		value,
		hasMatchingValue,
		additionalOnChangeAction,
		onChangeProp
	]);
	const onChange = useCallback((e, nextValue, reason) => {
		let resolvedValue = nextValue;
		if (freeSolo && isMultiple && reason === "create-option") {
			const values_0 = Array.isArray(nextValue) ? [...nextValue] : [];
			const raw_1 = values_0[values_0.length - 1];
			if (typeof raw_1 === "string") {
				const trimmed = raw_1.trim();
				values_0.pop();
				if (trimmed) {
					const formatted_0 = formatRawInput(trimmed);
					if (formatted_0 !== "" && formatted_0 !== null && formatted_0 !== void 0 && !hasMatchingValue(values_0, formatted_0)) values_0.push(formatted_0);
				}
				setInputValue("");
				resolvedValue = values_0;
			}
		}
		if (freeSolo && isMultiple && (reason === "select-option" || reason === "clear")) setInputValue("");
		if (additionalOnChangeAction) additionalOnChangeAction(resolvedValue);
		return onChangeProp?.(resolvedValue);
	}, [
		additionalOnChangeAction,
		freeSolo,
		isMultiple,
		formatRawInput,
		hasMatchingValue,
		onChangeProp
	]);
	const handleInputChange = useCallback((e_0, newInputValue, reason_0) => {
		const nextValue_0 = newInputValue ?? "";
		if (freeSolo && isMultiple && reason_0 === "reset") return;
		setInputValue(nextValue_0);
		if (!freeSolo || isMultiple) return;
		if (reason_0 === "input" || reason_0 === "clear") {
			if (additionalOnChangeAction) additionalOnChangeAction(nextValue_0);
			onChangeProp?.(nextValue_0);
		}
	}, [
		freeSolo,
		isMultiple,
		additionalOnChangeAction,
		onChangeProp
	]);
	const handleClose = useCallback((event, reason_1) => {
		if (!freeSolo) return;
		const raw_2 = (inputValue || "").trim();
		if (!raw_2) return;
		if (isMultiple) {
			if (reason_1 !== "blur") return;
			commitFreeSoloMultiple();
			return;
		}
		if (value && typeof value === "object") return;
		if (reason_1 === "blur" || reason_1 === "enter" || reason_1 === "create-option") {
			const updatedValue = formatRawInput(raw_2);
			if (additionalOnChangeAction) additionalOnChangeAction(updatedValue);
			onChangeProp?.(updatedValue);
		}
	}, [
		freeSolo,
		isMultiple,
		value,
		inputValue,
		formatRawInput,
		commitFreeSoloMultiple,
		additionalOnChangeAction,
		onChangeProp
	]);
	useEffect(() => {
		if (!freeSolo || isMultiple) return;
		if (value === null || value === void 0) {
			if (inputValue !== "") setInputValue("");
			return;
		}
		const nextValue_1 = typeof value === "string" ? value : getOptionLabel(value);
		if (nextValue_1 !== inputValue) setInputValue(nextValue_1 || "");
	}, [
		freeSolo,
		isMultiple,
		value,
		getOptionLabel,
		inputValue
	]);
	return /* @__PURE__ */ React.createElement(Autocomplete, {
		id: autoCompleteId,
		multiple: isMultiple,
		limitTags,
		disabled,
		options: options || [],
		getOptionLabel,
		getOptionSelected: (option_3, val) => optionKey ? option_3[optionKey] === val[optionKey] : option_3 === val,
		groupBy,
		onChange,
		inputValue: shouldControlInputValue ? inputValue : void 0,
		onInputChange: shouldControlInputValue ? handleInputChange : void 0,
		onClose: handleClose,
		value: value || (isMultiple ? [] : null),
		className: autocompleteRoot,
		classes: { root: classProps?.formControl },
		PopperComponent: customPopper || AutoCompletePopper,
		disableClearable,
		defaultValue,
		size,
		renderInput: (params) => /* @__PURE__ */ React.createElement(TextField, {
			...textFieldProps,
			...params,
			...other,
			inputProps: {
				...params.inputProps,
				udprecordid,
				onKeyDown: (event_0) => {
					params.inputProps?.onKeyDown?.(event_0);
					textFieldProps?.onKeyDown?.(event_0);
					if (event_0.defaultMuiPrevented) return;
					if (!freeSolo || !isMultiple) return;
					if (event_0.key !== "Enter") return;
					if (commitFreeSoloMultiple()) {
						event_0.preventDefault();
						event_0.stopPropagation();
					}
				}
			},
			label,
			margin: "dense",
			variant,
			placeholder,
			size: "small",
			InputProps: {
				...params.InputProps,
				...inputProps,
				classes: {
					root: classProps?.inputPropRoot,
					input: clsx(classes.formTextInput, classProps?.inputPropInput)
				}
			},
			InputLabelProps: { classes: { root: clsx(classes.labelRoot, classProps?.formLabelRoot) } }
		}),
		renderTags,
		filterOptions: filterOptionsProp || (freeSolo ? defaultFilterOptions : void 0),
		freeSolo
	});
};
//#endregion
export { FluentTextFieldAutoComplete };

//# sourceMappingURL=FluentTextFieldAutoComplete.mjs.map