import AddIcon from '../../../../../node_modules/@mui/icons-material/esm/AddRounded.mjs';
import React__default, { useMemo, useCallback, useState } from 'react';
import { Alert } from '../components/Alert.mjs';
import { Button } from '../components/Button.mjs';
import { Checkbox } from '../components/Checkbox.mjs';
import { FlexBox } from '../shared/components/FlexBox.mjs';
import { Input } from '../components/Input.mjs';
import { ListEditor } from '../components/ListEditor.mjs';
import { Modal } from '../components/Modal.mjs';
import { PaddingLeft } from '../components/PaddingLeft.mjs';
import { RadioGroup } from '../components/RadioGroup.mjs';
import { Select } from '../components/Select.mjs';
import { SettingsContainer, useSettingsContainer } from '../components/SettingsContainer.mjs';
import { SettingsSection } from '../components/SettingsSection.mjs';
import { Switch } from '../components/Switch.mjs';
import { Typography } from '../components/Typography.mjs';
import { arraysHaveSameContents } from '../utils/arraysHaveSameContents.mjs';
import { getDisplayKnownTenantProvider, getDisplayTenantProvider, getDisplayStatus } from '../utils/getDisplay.mjs';
import { isOauthMethod } from '../utils/isOauthMethod.mjs';
import { NO_VALUE } from '../utils/noValue.mjs';
import { ALL_OAUTH_TENANT_PROVIDERS, getMethodFromProvider } from '../utils/oAuthProviders.mjs';
import { useAllowedAuthMethods } from '../utils/useAllowedAuthMethods.mjs';
import { useConnections } from '../utils/useConnections.mjs';
import { useFormState } from '../utils/useFormState.mjs';
import { useMutateOrganization } from '../utils/useMutateOrganization.mjs';
import { useRbac } from '../utils/useRbac.mjs';
import { useSelf } from '../utils/useSelf.mjs';
import { useStateSliceSetter } from '../utils/useStateSliceSetter.mjs';
import { useOrgSettingsRouterController } from './AdminPortalOrgRouter.mjs';
import { useModalState } from '../shared/components/Modal.mjs';

const useMutateAuthSettings = ()=>{
    const { mutate } = useMutateOrganization();
    const setOrgAuthSettings = (mutatedProperties)=>{
        return mutate(mutatedProperties, {
            errorMessage: 'Failed to update email domain details.'
        });
    };
    return {
        setOrgAuthSettings
    };
};
const emailAllowedDomainsRenderer = [
    {
        title: 'Domain',
        getValue: (email)=>/*#__PURE__*/ React__default.createElement(Typography, {
                variant: "body2"
            }, email)
    }
];
const allowedConnectionsRenderers = ({ idToConnectionMap })=>[
        {
            title: 'Connection display name',
            getValue: (id)=>/*#__PURE__*/ React__default.createElement(Typography, {
                    variant: "body2"
                }, idToConnectionMap[id] ? idToConnectionMap[id].displayName : NO_VALUE)
        },
        {
            title: 'Status',
            getValue: (id)=>/*#__PURE__*/ React__default.createElement(Typography, {
                    variant: "body2"
                }, idToConnectionMap[id] ? getDisplayStatus(idToConnectionMap[id].status) : NO_VALUE)
        }
    ];
const emailInvitesLabelMap = {
    ALL_ALLOWED: 'Anybody',
    RESTRICTED: 'Users from allowed email domains'
};
const ssoJitProvisioningLabelMap = {
    ALL_ALLOWED: 'All SSO connections',
    RESTRICTED: 'Allowed SSO connections'
};
const PROVIDER_TENANT_ID_SEPARATOR = ':';
const serializeProviderAndTenantId = (providerType, tenantId)=>`${providerType}${PROVIDER_TENANT_ID_SEPARATOR}${tenantId}`;
const parseProviderAndTenantId = (providerAndTenantId)=>{
    const [provider, tenantId] = providerAndTenantId.split(PROVIDER_TENANT_ID_SEPARATOR, 2);
    return {
        provider,
        tenantId
    };
};
const EmailDomainsTable = ({ localState, remoteState, setLocalState, canSetAllowedDomains, editing })=>{
    const emailAllowedDomains = editing ? localState.emailAllowedDomains : remoteState.emailAllowedDomains;
    const [email, setEmail] = useState('');
    const addEmailModalProps = useModalState(()=>{
        setLocalState((state)=>({
                ...state,
                emailAllowedDomains: [
                    ...new Set([
                        ...localState.emailAllowedDomains,
                        email
                    ])
                ]
            }));
        setEmail('');
    });
    return /*#__PURE__*/ React__default.createElement(SettingsSection, {
        title: "Email domains",
        titleVariant: "h5",
        tooltipText: "Corporate email domains trusted by your company (e.g. acmecorp.com); used for both domain-restrictions on invites and JIT Provisioning by email domain if enabled."
    }, /*#__PURE__*/ React__default.createElement(Modal, {
        ...addEmailModalProps,
        title: "Add allowed email domain",
        confirmButtonText: "Save"
    }, /*#__PURE__*/ React__default.createElement(Input, {
        label: "Domain",
        onChange: setEmail,
        placeholder: "Enter domain",
        value: email
    })), /*#__PURE__*/ React__default.createElement(ListEditor, {
        items: emailAllowedDomains ?? [],
        itemRenderer: emailAllowedDomainsRenderer,
        onAdd: ()=>{
            addEmailModalProps.open();
        },
        emptyText: "No domains added.",
        getItemActionProps: editing && canSetAllowedDomains ? (item)=>({
                warningAction: {
                    text: 'Delete',
                    onClick: ()=>{
                        setEmail('');
                        setLocalState((prevState)=>({
                                ...prevState,
                                emailAllowedDomains: localState.emailAllowedDomains.filter((domain)=>domain !== item)
                            }));
                    }
                }
            }) : undefined,
        hideAddButton: !canSetAllowedDomains || !editing,
        addButtonText: "Add domain"
    }));
};
const SsoConnectionsTable = ({ localState, remoteState, setLocalState, editing, canSetSsoJitProvisioning })=>{
    const { data: canGetConnectionPerm } = useRbac('stytch.sso', 'get');
    const canGetConnection = !!canGetConnectionPerm;
    const { connections } = useConnections(canGetConnection);
    const { ssoAllowedConnections, ssoJitProvisioning } = editing ? localState : remoteState;
    const handleSsoJitProvisioningChange = useStateSliceSetter(setLocalState, 'ssoJitProvisioning');
    const [selectedSsoConnectionId, setSelectedSsoConnectionId] = useState(null);
    const idToConnectionMap = connections.reduce((acc, connection)=>{
        acc[connection.id] = connection;
        return acc;
    }, {});
    const selectedConnections = new Set(localState.ssoAllowedConnections);
    const availableConnections = connections.filter((val)=>!selectedConnections.has(val.id));
    const { open: openAddSsoConnectionModal, ...addSsoConnectionModalProps } = useModalState(()=>{
        if (selectedSsoConnectionId) {
            setLocalState((state)=>({
                    ...state,
                    ssoAllowedConnections: [
                        ...ssoAllowedConnections,
                        selectedSsoConnectionId
                    ]
                }));
            setSelectedSsoConnectionId(null);
        }
    });
    const ssoSelectItems = availableConnections.map((val)=>{
        return {
            label: val.displayName,
            value: val.id
        };
    });
    const ssoAllowedConnectionsRenderers = allowedConnectionsRenderers({
        idToConnectionMap
    });
    const showTable = ssoJitProvisioning === 'RESTRICTED';
    const renderAlert = ()=>{
        if (!canGetConnection) {
            return /*#__PURE__*/ React__default.createElement(Alert, null, "You do not have permission to view SSO Connections. Please contact your admin if you think this is a mistake.");
        }
        return null;
    };
    const renderListEditor = ()=>{
        if (!showTable) return null;
        return /*#__PURE__*/ React__default.createElement(ListEditor, {
            items: ssoAllowedConnections,
            itemRenderer: ssoAllowedConnectionsRenderers,
            onAdd: openAddSsoConnectionModal,
            emptyText: "No connections selected.",
            getItemActionProps: editing && canSetSsoJitProvisioning ? (item)=>({
                    warningAction: {
                        text: 'Remove',
                        onClick: ()=>{
                            setLocalState((prevState)=>({
                                    ...prevState,
                                    ssoAllowedConnections: prevState.ssoAllowedConnections.filter((val)=>val !== item)
                                }));
                        }
                    }
                }) : undefined,
            hideAddButton: !canSetSsoJitProvisioning || !editing,
            addButtonText: "Select connection"
        });
    };
    return /*#__PURE__*/ React__default.createElement(SettingsSection, {
        title: "SSO connections",
        titleVariant: "h5",
        tooltipText: "SAML or OIDC SSO Connections configured with your Workforce Identity Provider (e.g. Okta, Entra)"
    }, /*#__PURE__*/ React__default.createElement(RadioGroup, {
        onChange: (val)=>handleSsoJitProvisioningChange(val),
        value: ssoJitProvisioning,
        readOnly: !editing || !canSetSsoJitProvisioning,
        items: Object.entries(ssoJitProvisioningLabelMap).map(([value, label])=>{
            return {
                value,
                label
            };
        })
    }), /*#__PURE__*/ React__default.createElement(Modal, {
        ...addSsoConnectionModalProps,
        title: "Add allowed SSO connection",
        confirmButtonText: "Save",
        disableConfirm: !selectedSsoConnectionId
    }, /*#__PURE__*/ React__default.createElement(Select, {
        label: "SSO connection",
        selectItems: ssoSelectItems,
        value: selectedSsoConnectionId,
        onChange: setSelectedSsoConnectionId,
        placeholder: "Select"
    })), renderAlert(), renderListEditor());
};
const useOAuthAccountModal = ({ allowedOAuthTenants, onAddTenant })=>{
    const { self } = useSelf();
    const orgConfigAuthMethods = useAllowedAuthMethods();
    const linkedAccounts = useMemo(()=>self?.oauth_registrations.filter((registration)=>orgConfigAuthMethods.includes(getMethodFromProvider(registration.provider_type.toLowerCase()))).flatMap((registration)=>{
            const provider = registration.provider_type.toLowerCase();
            return registration.provider_tenants.filter((tenant)=>!allowedOAuthTenants[provider]?.some((tenantId)=>tenantId === tenant.tenant_id)).map((tenant)=>({
                    label: `${getDisplayTenantProvider(provider)} ${tenant.tenant_name} [${tenant.tenant_id}]`,
                    value: serializeProviderAndTenantId(provider, tenant.tenant_id),
                    provider,
                    tenantId: tenant.tenant_id
                }));
        }) ?? [], [
        allowedOAuthTenants,
        orgConfigAuthMethods,
        self?.oauth_registrations
    ]);
    const defaultManualMode = linkedAccounts.length === 0;
    const [isManualMode, setIsManualMode] = useState(defaultManualMode);
    // Inputs for manual mode
    const [manualInputProvider, setManualInputProvider] = useState();
    const [manualInputTenantId, setManualInputTenantId] = useState();
    // Input for linked account mode
    const [selectedLinkedAccountId, setSelectedLinkedAccountId] = useState();
    const { open, ...modalProps } = useModalState(()=>{
        const getInput = ()=>{
            if (isManualMode) {
                return {
                    provider: manualInputProvider,
                    tenantId: manualInputTenantId
                };
            } else if (selectedLinkedAccountId) {
                return parseProviderAndTenantId(selectedLinkedAccountId);
            }
        };
        const { provider, tenantId } = getInput() ?? {};
        if (provider && tenantId) {
            onAddTenant({
                provider,
                tenantId
            });
        }
    });
    const reset = ()=>{
        setManualInputProvider(undefined);
        setManualInputTenantId(undefined);
        setSelectedLinkedAccountId(undefined);
        setIsManualMode(defaultManualMode);
    };
    return {
        props: {
            ...modalProps,
            linkedAccounts,
            isManualMode,
            setIsManualMode,
            manualInputProvider,
            manualInputTenantId,
            setManualInputProvider,
            setManualInputTenantId,
            selectedLinkedAccountId,
            setSelectedLinkedAccountId
        },
        open,
        reset
    };
};
const OAuthAccountModal = ({ availableOAuthProviderSelectItems, linkedAccounts, isManualMode, setIsManualMode, manualInputProvider, manualInputTenantId, setManualInputProvider, setManualInputTenantId, selectedLinkedAccountId, setSelectedLinkedAccountId, ...modalProps })=>{
    const hasLinkedAccounts = linkedAccounts.length > 0;
    const linkedAccountSelectItems = useMemo(()=>linkedAccounts.map((account)=>({
                label: account.label,
                value: serializeProviderAndTenantId(account.provider, account.tenantId)
            })), [
        linkedAccounts
    ]);
    return /*#__PURE__*/ React__default.createElement(Modal, {
        ...modalProps,
        title: "Add allowed OAuth account",
        confirmButtonText: "Save"
    }, isManualMode ? /*#__PURE__*/ React__default.createElement(FlexBox, {
        gap: 2,
        flexDirection: "column"
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body2"
    }, "Add an OAuth account manually by selecting the OAuth provider and inputting the account ID."), /*#__PURE__*/ React__default.createElement(FlexBox, {
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(Select, {
        selectItems: availableOAuthProviderSelectItems,
        label: "OAuth Provider",
        value: manualInputProvider,
        onChange: setManualInputProvider
    }), /*#__PURE__*/ React__default.createElement(Input, {
        label: "Account ID",
        placeholder: "Enter account ID",
        value: manualInputTenantId ?? '',
        onChange: setManualInputTenantId
    })), hasLinkedAccounts && /*#__PURE__*/ React__default.createElement(Button, {
        variant: "text",
        startIcon: /*#__PURE__*/ React__default.createElement(AddIcon, null),
        onClick: ()=>setIsManualMode(false),
        compact: true
    }, "Add from linked accounts")) : /*#__PURE__*/ React__default.createElement(FlexBox, {
        gap: 2,
        flexDirection: "column"
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body2"
    }, "Select from the list of linked accounts."), /*#__PURE__*/ React__default.createElement(Select, {
        selectItems: linkedAccountSelectItems,
        label: "Account",
        value: selectedLinkedAccountId,
        onChange: setSelectedLinkedAccountId,
        fullWidth: true
    }), /*#__PURE__*/ React__default.createElement(Button, {
        variant: "text",
        startIcon: /*#__PURE__*/ React__default.createElement(AddIcon, null),
        onClick: ()=>setIsManualMode(true),
        compact: true
    }, "Add manually")));
};
const OAuthTenantsTable = ({ localState, remoteState, setLocalState, canSetOAuthTenants, editing })=>{
    const { allowedOAuthTenants } = editing ? localState : remoteState;
    const orgConfigAuthMethods = useAllowedAuthMethods();
    const allowedOAuthTenantsList = Object.entries(allowedOAuthTenants).flatMap(([provider, tenants])=>tenants.map((tenant)=>({
                provider,
                tenantId: tenant
            })));
    allowedOAuthTenantsList.sort((a, b)=>a.provider.localeCompare(b.provider));
    const { props: oauthModalProps, open, reset } = useOAuthAccountModal({
        allowedOAuthTenants,
        onAddTenant: ({ provider, tenantId })=>{
            setLocalState((prevState)=>({
                    ...prevState,
                    allowedOAuthTenants: {
                        ...allowedOAuthTenants,
                        [provider]: [
                            ...allowedOAuthTenants[provider] || [],
                            tenantId
                        ]
                    }
                }));
        }
    });
    const availableOAuthProviderSelectItems = ALL_OAUTH_TENANT_PROVIDERS.filter((provider)=>orgConfigAuthMethods.includes(getMethodFromProvider(provider))).map((provider)=>({
            label: getDisplayKnownTenantProvider(provider),
            value: provider
        }));
    const areOAuthProvidersAvailableToAdd = availableOAuthProviderSelectItems.length > 0;
    return /*#__PURE__*/ React__default.createElement(SettingsSection, {
        title: "OAuth accounts",
        titleVariant: "h5",
        tooltipText: "Your company's instance/organization/workspace on common OAuth providers (e.g. Slack workspace, Github organization)."
    }, /*#__PURE__*/ React__default.createElement(OAuthAccountModal, {
        ...oauthModalProps,
        availableOAuthProviderSelectItems: availableOAuthProviderSelectItems
    }), /*#__PURE__*/ React__default.createElement(ListEditor, {
        items: allowedOAuthTenantsList,
        rowKeyExtractor: (item)=>serializeProviderAndTenantId(item.provider, item.tenantId),
        emptyText: "No accounts added.",
        itemRenderer: [
            {
                title: 'OAuth Provider',
                getValue: (item)=>/*#__PURE__*/ React__default.createElement(Typography, {
                        variant: "body2"
                    }, getDisplayTenantProvider(item.provider))
            },
            {
                title: 'Allowed Tenants',
                getValue: (item)=>/*#__PURE__*/ React__default.createElement(Typography, {
                        variant: "body2"
                    }, item.tenantId)
            }
        ],
        onAdd: ()=>{
            reset();
            open();
        },
        getItemActionProps: editing && canSetOAuthTenants ? ({ provider, tenantId })=>({
                warningAction: {
                    text: 'Delete',
                    onClick: ()=>{
                        setLocalState((prevState)=>{
                            return {
                                ...prevState,
                                allowedOAuthTenants: {
                                    ...prevState.allowedOAuthTenants,
                                    [provider]: prevState.allowedOAuthTenants[provider].filter((val)=>val !== tenantId)
                                }
                            };
                        });
                    }
                }
            }) : undefined,
        hideAddButton: !canSetOAuthTenants || !editing || !areOAuthProvidersAvailableToAdd,
        addButtonText: "Add account"
    }));
};
const OrgSettingsUserOnboardingBody = ({ canSetEmailInvites, canSetEmailJitProvisioning, canSetAllowedDomains, canSetSsoJitProvisioning, canSetOAuthTenants, canSetOAuthTenantJitProvisioning, localState, remoteState, setLocalState })=>{
    const { editing } = useSettingsContainer();
    const { emailInvites, isEmailJitProvisioningAllowed, ssoJitProvisioning, isOauthTenantJitProvisioningAllowed, allowedOAuthTenants } = editing ? localState : remoteState;
    const handleEmailJitProvisioningChange = useStateSliceSetter(setLocalState, 'isEmailJitProvisioningAllowed');
    const handleEmailInvitesChange = useStateSliceSetter(setLocalState, 'emailInvites');
    const handleSsoJitProvisioningChange = useStateSliceSetter(setLocalState, 'ssoJitProvisioning');
    const handleOAuthTenantJitProvisioningChange = useStateSliceSetter(setLocalState, 'isOauthTenantJitProvisioningAllowed');
    const orgConfigAuthMethods = useAllowedAuthMethods();
    const ssoIsAllowedAuthMethod = useMemo(()=>orgConfigAuthMethods.includes('sso'), [
        orgConfigAuthMethods
    ]);
    const oauthIsAllowedAuthMethod = useMemo(()=>orgConfigAuthMethods.some(isOauthMethod), [
        orgConfigAuthMethods
    ]);
    const areOAuthProvidersAvailableToAdd = useMemo(()=>{
        return ALL_OAUTH_TENANT_PROVIDERS.some((provider)=>orgConfigAuthMethods.includes(getMethodFromProvider(provider)));
    }, [
        orgConfigAuthMethods
    ]);
    const oauthProvidersExist = Object.keys(allowedOAuthTenants).length > 0;
    const showEmailTable = emailInvites === 'RESTRICTED' || isEmailJitProvisioningAllowed;
    const showOAuthTable = isOauthTenantJitProvisioningAllowed && oauthIsAllowedAuthMethod && (areOAuthProvidersAvailableToAdd || oauthProvidersExist);
    const showSsoComponents = ssoJitProvisioning !== 'NOT_ALLOWED' && ssoIsAllowedAuthMethod;
    const showOAuthJitCheckbox = oauthIsAllowedAuthMethod && (areOAuthProvidersAvailableToAdd || oauthProvidersExist);
    const showSsoJitCheckbox = ssoIsAllowedAuthMethod;
    return /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(SettingsSection, {
        title: "Invites"
    }, /*#__PURE__*/ React__default.createElement(Switch, {
        readOnly: !editing || !canSetEmailInvites,
        label: 'Allow members to be invited by email',
        checked: emailInvites !== 'NOT_ALLOWED',
        onChange: (value)=>handleEmailInvitesChange(value ? 'ALL_ALLOWED' : 'NOT_ALLOWED')
    }), emailInvites !== 'NOT_ALLOWED' && /*#__PURE__*/ React__default.createElement(PaddingLeft, null, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "row",
        flexWrap: "wrap"
    }, /*#__PURE__*/ React__default.createElement(RadioGroup, {
        onChange: handleEmailInvitesChange,
        value: emailInvites,
        readOnly: !editing || !canSetEmailInvites,
        items: Object.entries(emailInvitesLabelMap).map(([value, label])=>{
            return {
                value,
                label
            };
        })
    })))), /*#__PURE__*/ React__default.createElement(SettingsSection, {
        title: "JIT Provisioning",
        tooltipText: "If JIT provisioning is enabled, users who successfully authenticate using the specified methods will be automatically granted an account if they do not already exist."
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body2"
    }, "Allow users to automatically join based on your access control list"), /*#__PURE__*/ React__default.createElement(PaddingLeft, null, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "row",
        flexWrap: "wrap"
    }, /*#__PURE__*/ React__default.createElement(Checkbox, {
        disabled: !editing || !canSetEmailJitProvisioning,
        label: "Email domains",
        checked: isEmailJitProvisioningAllowed,
        onClick: handleEmailJitProvisioningChange
    }), showOAuthJitCheckbox && /*#__PURE__*/ React__default.createElement(Checkbox, {
        disabled: !editing || !canSetOAuthTenantJitProvisioning,
        label: "OAuth accounts",
        checked: isOauthTenantJitProvisioningAllowed,
        onClick: handleOAuthTenantJitProvisioningChange
    }), showSsoJitCheckbox && /*#__PURE__*/ React__default.createElement(Checkbox, {
        disabled: !editing || !canSetSsoJitProvisioning,
        label: "SSO connections",
        checked: ssoJitProvisioning !== 'NOT_ALLOWED',
        onClick: (value)=>handleSsoJitProvisioningChange(value ? 'RESTRICTED' : 'NOT_ALLOWED')
    })))), (showEmailTable || showOAuthTable || showSsoComponents) && /*#__PURE__*/ React__default.createElement(SettingsSection, {
        title: "Access control list"
    }, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: editing ? 1 : 3
    }, showEmailTable && /*#__PURE__*/ React__default.createElement(EmailDomainsTable, {
        localState: localState,
        remoteState: remoteState,
        setLocalState: setLocalState,
        canSetAllowedDomains: canSetAllowedDomains,
        editing: editing
    }), showOAuthTable && /*#__PURE__*/ React__default.createElement(OAuthTenantsTable, {
        localState: localState,
        remoteState: remoteState,
        setLocalState: setLocalState,
        canSetOAuthTenants: canSetOAuthTenants,
        editing: editing
    }), showSsoComponents && /*#__PURE__*/ React__default.createElement(SsoConnectionsTable, {
        localState: localState,
        remoteState: remoteState,
        setLocalState: setLocalState,
        canSetSsoJitProvisioning: canSetSsoJitProvisioning,
        editing: editing
    }))));
};
const OrgSettingsUserOnboardingSection = ({ orgInfo })=>{
    const { data: canSetEmailJitProvisioning } = useRbac('stytch.organization', 'update.settings.email-jit-provisioning');
    const { data: canSetSsoJitProvisioning } = useRbac('stytch.organization', 'update.settings.sso-jit-provisioning');
    const { data: canSetOAuthTenantJitProvisioning } = useRbac('stytch.organization', 'update.settings.oauth-tenant-jit-provisioning');
    const { data: canSetEmailInvites } = useRbac('stytch.organization', 'update.settings.email-invites');
    const { data: canSetAllowedDomains } = useRbac('stytch.organization', 'update.settings.allowed-domains');
    const { data: canSetOAuthTenants } = useRbac('stytch.organization', 'update.settings.allowed-oauth-tenants');
    const remoteState = useMemo(()=>({
            emailInvites: orgInfo.email_invites,
            emailAllowedDomains: orgInfo.email_allowed_domains,
            isEmailJitProvisioningAllowed: orgInfo.email_jit_provisioning !== 'NOT_ALLOWED',
            ssoJitProvisioning: orgInfo.sso_jit_provisioning,
            ssoAllowedConnections: orgInfo.sso_jit_provisioning_allowed_connections,
            isOauthTenantJitProvisioningAllowed: orgInfo.oauth_tenant_jit_provisioning !== 'NOT_ALLOWED',
            allowedOAuthTenants: orgInfo.allowed_oauth_tenants
        }), [
        orgInfo
    ]);
    const { localState, setLocalState, editing, handleSetEditing } = useFormState({
        remoteState
    });
    const { setOrgAuthSettings } = useMutateAuthSettings();
    const { useBlockNavigation } = useOrgSettingsRouterController();
    const handleSave = useCallback(async ()=>{
        const mutatedProperties = {};
        if (localState.isEmailJitProvisioningAllowed !== remoteState.isEmailJitProvisioningAllowed) {
            mutatedProperties.email_jit_provisioning = localState.isEmailJitProvisioningAllowed ? 'RESTRICTED' : 'NOT_ALLOWED';
        }
        if (localState.emailInvites !== remoteState.emailInvites) {
            mutatedProperties.email_invites = localState.emailInvites;
        }
        if (!arraysHaveSameContents(localState.emailAllowedDomains, remoteState.emailAllowedDomains)) {
            mutatedProperties.email_allowed_domains = localState.emailAllowedDomains;
        }
        if (localState.ssoJitProvisioning !== remoteState.ssoJitProvisioning) {
            mutatedProperties.sso_jit_provisioning = localState.ssoJitProvisioning;
        }
        if (!arraysHaveSameContents(localState.ssoAllowedConnections, remoteState.ssoAllowedConnections)) {
            mutatedProperties.sso_jit_provisioning_allowed_connections = localState.ssoAllowedConnections;
        }
        if (localState.isOauthTenantJitProvisioningAllowed !== remoteState.isOauthTenantJitProvisioningAllowed) {
            mutatedProperties.oauth_tenant_jit_provisioning = localState.isOauthTenantJitProvisioningAllowed ? 'RESTRICTED' : 'NOT_ALLOWED';
        }
        if (!arraysHaveSameContents(Object.entries(localState.allowedOAuthTenants), Object.entries(remoteState.allowedOAuthTenants))) {
            mutatedProperties.allowed_oauth_tenants = localState.allowedOAuthTenants;
        }
        if (Object.keys(mutatedProperties).length > 0) {
            await setOrgAuthSettings(mutatedProperties);
        }
    }, [
        localState.allowedOAuthTenants,
        localState.emailAllowedDomains,
        localState.emailInvites,
        localState.isEmailJitProvisioningAllowed,
        localState.isOauthTenantJitProvisioningAllowed,
        localState.ssoAllowedConnections,
        localState.ssoJitProvisioning,
        remoteState.allowedOAuthTenants,
        remoteState.emailAllowedDomains,
        remoteState.emailInvites,
        remoteState.isEmailJitProvisioningAllowed,
        remoteState.isOauthTenantJitProvisioningAllowed,
        remoteState.ssoAllowedConnections,
        remoteState.ssoJitProvisioning,
        setOrgAuthSettings
    ]);
    const disableSave = useMemo(()=>{
        return arraysHaveSameContents(localState.emailAllowedDomains, remoteState.emailAllowedDomains) && localState.emailInvites === remoteState.emailInvites && localState.isEmailJitProvisioningAllowed === remoteState.isEmailJitProvisioningAllowed && localState.ssoJitProvisioning === remoteState.ssoJitProvisioning && arraysHaveSameContents(localState.ssoAllowedConnections, remoteState.ssoAllowedConnections) && localState.isOauthTenantJitProvisioningAllowed === remoteState.isOauthTenantJitProvisioningAllowed && arraysHaveSameContents(Object.entries(localState.allowedOAuthTenants), Object.entries(remoteState.allowedOAuthTenants));
    }, [
        localState.allowedOAuthTenants,
        localState.emailAllowedDomains,
        localState.emailInvites,
        localState.isEmailJitProvisioningAllowed,
        localState.isOauthTenantJitProvisioningAllowed,
        localState.ssoAllowedConnections,
        localState.ssoJitProvisioning,
        remoteState.allowedOAuthTenants,
        remoteState.emailAllowedDomains,
        remoteState.emailInvites,
        remoteState.isEmailJitProvisioningAllowed,
        remoteState.isOauthTenantJitProvisioningAllowed,
        remoteState.ssoAllowedConnections,
        remoteState.ssoJitProvisioning
    ]);
    return /*#__PURE__*/ React__default.createElement(SettingsContainer, {
        hasCTA: canSetEmailJitProvisioning || canSetEmailInvites || canSetAllowedDomains || canSetSsoJitProvisioning || canSetOAuthTenants || canSetOAuthTenantJitProvisioning,
        title: "User onboarding",
        onSave: handleSave,
        useBlockNavigation: useBlockNavigation,
        editing: editing,
        setEditing: handleSetEditing,
        disableSave: disableSave
    }, /*#__PURE__*/ React__default.createElement(OrgSettingsUserOnboardingBody, {
        canSetEmailJitProvisioning: canSetEmailJitProvisioning,
        canSetEmailInvites: canSetEmailInvites,
        canSetAllowedDomains: canSetAllowedDomains,
        canSetSsoJitProvisioning: canSetSsoJitProvisioning,
        canSetOAuthTenantJitProvisioning: canSetOAuthTenantJitProvisioning,
        canSetOAuthTenants: canSetOAuthTenants,
        localState: localState,
        remoteState: remoteState,
        setLocalState: setLocalState
    }));
};

export { OrgSettingsUserOnboardingSection };
//# sourceMappingURL=OrgSettingsUserOnboardingSection.mjs.map
