import { ConfigService } from "../../../configService/index.mjs";
import { useHandleAxiosSnackbar } from "../../../utilities/apiHelpers.mjs";
import { apiMutate } from "../../../utilities/useAxiosMutate.mjs";
import { SideSheet } from "../../../UI/surfaces/SideSheet.mjs";
import { useTenant } from "../../../utilities/tenant/useTenant.mjs";
import { UserForm } from "./form/UserForm.mjs";
import React, { useCallback, useState } from "react";
import "notistack";
import { useTranslation } from "react-i18next";
import { cloneDeep } from "lodash-es";
//#region src/shell/ui/user/UserFormSideSheet.jsx
const UserFormSideSheet = ({ open, onClose }) => {
	const [loading, setLoading] = useState(false);
	const tenant = useTenant();
	const { t } = useTranslation();
	const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
	const getUserByEmail = useCallback(async (email) => {
		return await apiMutate(ConfigService.securityV1ApiUrl, `users/email/${email}`, { method: "get" });
	}, []);
	const createUser = useCallback(async (data) => {
		return await apiMutate(ConfigService.securityV1ApiUrl, `users/${tenant?.activeTenant?.tenantId ?? ""}`, { method: "post" }, data);
	}, [tenant]);
	const inviteUser = useCallback(async (data_0) => {
		return await apiMutate(ConfigService.securityV1ApiUrl, `users/${tenant?.activeTenant?.tenantId ?? ""}/invite`, { method: "post" }, data_0);
	}, [tenant]);
	const addUserToTenant = useCallback(async (email_0) => {
		return await apiMutate(ConfigService.tenantV1ApiUrl, `tenants/${tenant?.activeTenant?.tenantId ?? ""}/${email_0}`, { method: "post" });
	}, [tenant]);
	const updateExistingUser = useCallback(async (data_1) => {
		return await apiMutate(ConfigService.securityV1ApiUrl, `users/aad/${data_1.id}`, { method: "patch" }, data_1);
	}, []);
	const fillInValues = (oldValues, newValues) => {
		const invalidFields = [
			"id",
			"displayName",
			"mail",
			"userType",
			"email",
			"accountEnabled",
			"mailNickname",
			"identities",
			"password",
			"passwordProfile",
			"unityId",
			"unityDefaultTenantId"
		];
		for (let field in oldValues) if (!invalidFields.includes(field)) {
			if (!oldValues[field]) oldValues[field] = newValues[field];
		}
		return oldValues;
	};
	const handleSubmit = useCallback(async (values) => {
		setLoading(true);
		try {
			if (values.email) values.email = values.email.toLowerCase().trim();
			const userExists = (await getUserByEmail(values.email)).data;
			if (userExists) {
				await updateExistingUser({ data: fillInValues(cloneDeep(userExists), values) });
				await addUserToTenant(values.email);
				handleSuccessSnackbar(t("User has been updated and added to the tenant"));
			} else if (values.isInvite) {
				await inviteUser({ data: values });
				handleSuccessSnackbar(t("User invitation sent successfully"));
			} else {
				await createUser({ data: values });
				handleSuccessSnackbar(t("User has been created successfully"));
			}
			onClose();
		} catch (error) {
			handleErrorSnackbar(error.message || t("An error occurred, please ensure you are creating a new user"));
		} finally {
			setLoading(false);
		}
	}, [
		getUserByEmail,
		createUser,
		inviteUser,
		addUserToTenant,
		updateExistingUser,
		handleErrorSnackbar,
		handleSuccessSnackbar,
		onClose,
		t
	]);
	return /* @__PURE__ */ React.createElement(SideSheet, {
		open,
		onClose,
		title: t("Add User"),
		width: 600
	}, /* @__PURE__ */ React.createElement(UserForm, {
		submitUser: handleSubmit,
		creatingUser: loading,
		tenant: tenant?.activeTenant
	}));
};
//#endregion
export { UserFormSideSheet as default };

//# sourceMappingURL=UserFormSideSheet.mjs.map