import React, { useCallback, useState } from 'react';
import { SideSheet } from '../../../UI/surfaces/SideSheet';
import { UserForm } from './form/UserForm';
import { useSnackbar } from 'notistack';
import { apiMutate } from '../../../utilities/useAxiosMutate';
import { useTenant } from '../../../utilities/tenant/useTenant';
import { useHandleAxiosSnackbar } from '../../../utilities/apiHelpers';
import { cloneDeep } from 'lodash-es';
import { useTranslation } from 'react-i18next';
import { ConfigService } from '../../../configService';
const UserFormSideSheet = ({ open, onClose, }) => {
    const [loading, setLoading] = useState(false);
    const tenant = useTenant();
    const { t } = useTranslation();
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    // Helper functions
    const getUserByEmail = useCallback(async email => {
        return await apiMutate(ConfigService.securityV1ApiUrl, `users/email/${email}`, { method: 'get' });
    }, []);
    const createUser = useCallback(async data => {
        var _a;
        var _b;
        return await apiMutate(ConfigService.securityV1ApiUrl, `users/${(_b = (_a = tenant === null || tenant === void 0 ? void 0 : tenant.activeTenant) === null || _a === void 0 ? void 0 : _a.tenantId) !== null && _b !== void 0 ? _b : ''}`, { method: 'post' }, data);
    }, [tenant]);
    const inviteUser = useCallback(async data => {
        var _a;
        var _b;
        return await apiMutate(ConfigService.securityV1ApiUrl, `users/${(_b = (_a = tenant === null || tenant === void 0 ? void 0 : tenant.activeTenant) === null || _a === void 0 ? void 0 : _a.tenantId) !== null && _b !== void 0 ? _b : ''}/invite`, { method: 'post' }, data);
    }, [tenant]);
    const addUserToTenant = useCallback(async email => {
        var _a;
        var _b;
        return await apiMutate(ConfigService.tenantV1ApiUrl, `tenants/${(_b = (_a = tenant === null || tenant === void 0 ? void 0 : tenant.activeTenant) === null || _a === void 0 ? void 0 : _a.tenantId) !== null && _b !== void 0 ? _b : ''}/${email}`, { method: 'post' });
    }, [tenant]);
    const updateExistingUser = useCallback(async data => {
        return await apiMutate(ConfigService.securityV1ApiUrl, `users/aad/${data.id}`, { method: 'patch' }, data);
    }, []);
    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 userExistsResponse = await getUserByEmail(values.email);
            const userExists = userExistsResponse.data;
            if (userExists) {
                const existingUser = cloneDeep(userExists);
                const updatedValues = fillInValues(existingUser, values);
                // Update existing user and add to tenant
                await updateExistingUser({ data: updatedValues });
                await addUserToTenant(values.email);
                handleSuccessSnackbar(t('User has been updated and added to the tenant'));
            }
            else {
                // Check if this is an invite flow or standard create
                if (values.isInvite) {
                    await inviteUser({ data: values });
                    handleSuccessSnackbar(t('User invitation sent successfully'));
                }
                else {
                    // Create a new user
                    await createUser({ data: values });
                    handleSuccessSnackbar(t('User has been created successfully'));
                }
            }
            onClose(); // Close the SideSheet after successful submission
        }
        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 (React.createElement(SideSheet, { open: open, onClose: onClose, title: t("Add User"), width: 600 }, React.createElement(UserForm, { submitUser: handleSubmit, creatingUser: loading, tenant: tenant === null || tenant === void 0 ? void 0 : tenant.activeTenant })));
};
export default UserFormSideSheet;
//# sourceMappingURL=UserFormSideSheet.js.map