import React, { useCallback, useEffect, useState } from "react";
import { Chip, TextField } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";
//#region src/shell/ui/user/form/UserRoleAutoComplete.jsx
const UserRoleAutoComplete = (props) => {
	const { id, label, placeholder, options, textFieldProps, disabled, onChange: onChangeProp, initialValue, value, optionLabel, groupBy, userRoles, setUserRoles, isFormField = false, ...other } = props;
	const [acValue, setACValue] = useState(initialValue);
	const onChange = useCallback((e, value_0) => onChangeProp?.(value_0), [onChangeProp]);
	const parseMultiple = useCallback((value_1) => value_1, []);
	const formatMultiple = useCallback((...args) => args[0] || [], []);
	const handleChange = (e_0, value_2) => {
		onChange(e_0, value_2);
		if (userRoles && setUserRoles) {
			const userId = id.replace("_role", "");
			const updatedUserRoles = [...userRoles];
			const userRole = updatedUserRoles.find((ur) => ur.id === userId);
			if (userRole) userRole.roles = value_2;
			else updatedUserRoles.push({
				id: userId,
				roles: value_2
			});
			setUserRoles(updatedUserRoles);
			setACValue(value_2);
		} else setACValue(value_2);
	};
	useEffect(() => {
		if (!userRoles) return;
		const userId_0 = id.replace("_role", "");
		const foundUserRole = userRoles.find((ur_0) => ur_0.id === userId_0);
		if (foundUserRole) {
			const roleIds = foundUserRole.roles.map((role) => role.roleId);
			setACValue(options.filter((option) => roleIds.includes(option.roleId)));
		}
	}, [
		options,
		userRoles,
		id
	]);
	useEffect(() => {
		if (isFormField && initialValue) {
			onChange(null, initialValue);
			setACValue(initialValue);
		}
	}, [initialValue, isFormField]);
	return /* @__PURE__ */ React.createElement(Autocomplete, {
		multiple: true,
		id,
		disabled,
		options: options || [],
		getOptionLabel: optionLabel ? (option_0) => option_0[optionLabel] || "" : (option_1) => option_1.name,
		onChange: (e_1, value_3) => handleChange(e_1, value_3),
		value: acValue,
		groupBy: groupBy ? (option_2) => option_2[groupBy] : "",
		parse: parseMultiple,
		format: formatMultiple,
		renderTags: (value_4, getTagProps) => value_4.map((option_3, index) => /* @__PURE__ */ React.createElement(Chip, {
			key: index,
			color: "primary",
			label: /* @__PURE__ */ React.createElement("span", { style: { color: "white" } }, optionLabel ? option_3[optionLabel] ? option_3[optionLabel] : "" : option_3),
			...getTagProps({ index })
		})),
		renderInput: (params) => /* @__PURE__ */ React.createElement(TextField, {
			...textFieldProps,
			...params,
			...other,
			label,
			variant: "outlined",
			fullWidth: true,
			size: "small"
		})
	});
};
//#endregion
export { UserRoleAutoComplete };

//# sourceMappingURL=UserRoleAutoComplete.mjs.map