import React__default, { useMemo, useCallback } from 'react';
import { Alert } from '../components/Alert.mjs';
import { Checkbox } from '../components/Checkbox.mjs';
import { FlexBox } from '../shared/components/FlexBox.mjs';
import { PaddingLeft } from '../components/PaddingLeft.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 { useAdminPortalConfig } from '../utils/useAdminPortalConfig.mjs';
import { useAllowedAuthMethods } from '../utils/useAllowedAuthMethods.mjs';
import { useAllowedMfaMethods } from '../utils/useAllowedMfaMethods.mjs';
import { useFormState } from '../utils/useFormState.mjs';
import { useMutateOrganization } from '../utils/useMutateOrganization.mjs';
import { useRbac } from '../utils/useRbac.mjs';
import { useOrgSettingsRouterController } from './AdminPortalOrgRouter.mjs';

const allowedAuthMethodsLabelMap = {
    magic_link: 'Email Magic Links',
    sso: 'Single Sign-On',
    google_oauth: 'Google OAuth',
    microsoft_oauth: 'Microsoft OAuth',
    hubspot_oauth: 'HubSpot OAuth',
    slack_oauth: 'Slack OAuth',
    github_oauth: 'GitHub OAuth',
    password: 'Password',
    email_otp: 'Email OTP'
};
const allowedMfaMethodsLabelMap = {
    sms_otp: 'SMS OTP',
    totp: 'TOTP'
};
const useMutateAuthSettings$1 = ()=>{
    const { mutate } = useMutateOrganization();
    const setOrgAuthSettings = (mutatedProperties)=>{
        return mutate(mutatedProperties, {
            errorMessage: 'Failed to update authorization details.'
        });
    };
    return {
        setOrgAuthSettings
    };
};
const OrgSettingsAuthenticationSettingsBody = ({ orgConfigAuthMethods, orgConfigMfaMethods, canSetAllowedAuthMethods, canSetMfaPolicy, canSetAllowedMfaMethods, mfaPolicyConfig, localState, setLocalState })=>{
    const { editing } = useSettingsContainer();
    const handlePrimaryAuthChange = (value)=>{
        setLocalState((prevState)=>({
                ...prevState,
                isPrimaryAuthAllAllowed: value
            }));
    };
    const handleMfaPolicyChange = (value)=>{
        setLocalState((prevState)=>({
                ...prevState,
                isMfaPolicyRequiredForAll: value
            }));
    };
    const handleSecondaryAuthChange = (value)=>{
        setLocalState((prevState)=>({
                ...prevState,
                isSecondaryAuthAllAllowed: value
            }));
    };
    const isAuthMethodChecked = (authMethod)=>{
        return localState.allowedAuthMethods?.includes(authMethod);
    };
    const isMfaMethodChecked = (mfaMethod)=>{
        return localState.allowedMfaMethods?.includes(mfaMethod);
    };
    const handleAllowedAuthMethodClick = (authMethod)=>{
        if (localState.allowedAuthMethods.includes(authMethod)) {
            setLocalState((prevState)=>({
                    ...prevState,
                    allowedAuthMethods: prevState.allowedAuthMethods.filter((method)=>method !== authMethod)
                }));
        } else {
            setLocalState((prevState)=>({
                    ...prevState,
                    allowedAuthMethods: [
                        ...prevState.allowedAuthMethods,
                        authMethod
                    ]
                }));
        }
    };
    const handleAllowedMfaMethodClick = (mfaMethod)=>{
        if (localState.allowedMfaMethods.includes(mfaMethod)) {
            setLocalState((prevState)=>({
                    ...prevState,
                    allowedMfaMethods: prevState.allowedMfaMethods?.filter((method)=>method !== mfaMethod)
                }));
        } else {
            setLocalState((prevState)=>({
                    ...prevState,
                    allowedMfaMethods: [
                        ...prevState?.allowedMfaMethods ?? [],
                        mfaMethod
                    ]
                }));
        }
    };
    return /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(SettingsSection, {
        title: "Primary authentication"
    }, editing && !localState.isPrimaryAuthAllAllowed && !!localState.allowedAuthMethods && localState.allowedAuthMethods.length === 0 && /*#__PURE__*/ React__default.createElement(Alert, null, 'Please select at least one primary authentication method.'), /*#__PURE__*/ React__default.createElement(Switch, {
        readOnly: !editing || !canSetAllowedAuthMethods,
        label: 'Allow all primary auth methods',
        checked: localState.isPrimaryAuthAllAllowed,
        onChange: handlePrimaryAuthChange
    }), !localState.isPrimaryAuthAllAllowed && /*#__PURE__*/ React__default.createElement(PaddingLeft, null, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "row",
        flexWrap: "wrap"
    }, orgConfigAuthMethods.map((authMethod)=>{
        const label = allowedAuthMethodsLabelMap[authMethod];
        return /*#__PURE__*/ React__default.createElement(Checkbox, {
            key: authMethod,
            label: label,
            disabled: !editing,
            checked: isAuthMethodChecked(authMethod),
            onClick: ()=>handleAllowedAuthMethodClick(authMethod)
        });
    })))), mfaPolicyConfig && /*#__PURE__*/ React__default.createElement(SettingsSection, {
        title: "Secondary authentication"
    }, editing && !localState.isSecondaryAuthAllAllowed && !!localState.allowedMfaMethods && localState.allowedMfaMethods.length === 0 && /*#__PURE__*/ React__default.createElement(Alert, null, 'Please select at least one secondary authentication method.'), /*#__PURE__*/ React__default.createElement(Typography, {
        variant: 'body2'
    }, 'All members logging in will be required to set up one of the allowed secondary auth methods.'), /*#__PURE__*/ React__default.createElement(Switch, {
        readOnly: !editing || !canSetMfaPolicy,
        label: 'Require MFA for all users',
        checked: localState.isMfaPolicyRequiredForAll,
        onChange: handleMfaPolicyChange
    }), /*#__PURE__*/ React__default.createElement(Switch, {
        readOnly: !editing || !canSetAllowedMfaMethods,
        label: 'Allow all secondary auth methods',
        checked: localState.isSecondaryAuthAllAllowed,
        onChange: handleSecondaryAuthChange
    }), !localState.isSecondaryAuthAllAllowed && /*#__PURE__*/ React__default.createElement(PaddingLeft, null, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "row",
        flexWrap: "wrap"
    }, orgConfigMfaMethods.map((authMethod)=>{
        const label = allowedMfaMethodsLabelMap[authMethod];
        return /*#__PURE__*/ React__default.createElement(Checkbox, {
            key: authMethod,
            label: label,
            disabled: !editing || !canSetAllowedMfaMethods,
            checked: isMfaMethodChecked(authMethod),
            onClick: ()=>handleAllowedMfaMethodClick(authMethod)
        });
    })))));
};
const OrgSettingsAuthenticationSettingsSection = ({ orgInfo })=>{
    const { data: canSetAllowedAuthMethods } = useRbac('stytch.organization', 'update.settings.allowed-auth-methods');
    const { data: canSetMfaPolicy } = useRbac('stytch.organization', 'update.settings.mfa-policy');
    const { data: canSetAllowedMfaMethods } = useRbac('stytch.organization', 'update.settings.allowed-mfa-methods');
    const { setOrgAuthSettings } = useMutateAuthSettings$1();
    const { data: adminPortalConfig } = useAdminPortalConfig({
        shouldFetch: true
    });
    const mfaPolicyConfig = adminPortalConfig?.organization_config.mfa_controls_enabled;
    const orgConfigAuthMethods = useAllowedAuthMethods();
    const orgConfigMfaMethods = useAllowedMfaMethods();
    const remoteState = useMemo(()=>({
            authMethods: orgInfo.auth_methods,
            allowedAuthMethods: orgInfo.allowed_auth_methods,
            mfaPolicy: orgInfo.mfa_policy,
            mfaMethods: orgInfo.mfa_methods,
            allowedMfaMethods: orgInfo.allowed_mfa_methods,
            isPrimaryAuthAllAllowed: orgInfo.auth_methods === 'ALL_ALLOWED',
            isSecondaryAuthAllAllowed: orgInfo.mfa_methods === 'ALL_ALLOWED',
            isMfaPolicyRequiredForAll: orgInfo.mfa_policy === 'REQUIRED_FOR_ALL'
        }), [
        orgInfo.allowed_auth_methods,
        orgInfo.allowed_mfa_methods,
        orgInfo.auth_methods,
        orgInfo.mfa_methods,
        orgInfo.mfa_policy
    ]);
    const { localState, setLocalState, editing, handleSetEditing } = useFormState({
        remoteState
    });
    const { useBlockNavigation } = useOrgSettingsRouterController();
    const handleSave = useCallback(async ()=>{
        const mutatedProperties = {};
        if (localState.isPrimaryAuthAllAllowed !== remoteState.isPrimaryAuthAllAllowed) {
            mutatedProperties.auth_methods = localState.isPrimaryAuthAllAllowed ? 'ALL_ALLOWED' : 'RESTRICTED';
        }
        if (!arraysHaveSameContents(localState.allowedAuthMethods, remoteState.allowedAuthMethods)) {
            mutatedProperties.allowed_auth_methods = localState.allowedAuthMethods;
        }
        if (localState.isSecondaryAuthAllAllowed !== remoteState.isSecondaryAuthAllAllowed) {
            mutatedProperties.mfa_methods = localState.isSecondaryAuthAllAllowed ? 'ALL_ALLOWED' : 'RESTRICTED';
        }
        if (!arraysHaveSameContents(localState.allowedMfaMethods, remoteState.allowedMfaMethods)) {
            mutatedProperties.allowed_mfa_methods = localState.allowedMfaMethods;
        }
        if (localState.isMfaPolicyRequiredForAll !== remoteState.isMfaPolicyRequiredForAll) {
            mutatedProperties.mfa_policy = localState.isMfaPolicyRequiredForAll ? 'REQUIRED_FOR_ALL' : 'OPTIONAL';
        }
        if (Object.keys(mutatedProperties).length > 0) {
            await setOrgAuthSettings(mutatedProperties);
        }
    }, [
        localState,
        remoteState,
        setOrgAuthSettings
    ]);
    const handleCancel = useCallback(()=>{
        setLocalState(remoteState);
    }, [
        remoteState,
        setLocalState
    ]);
    const disableSave = useMemo(()=>{
        const isDeepEqual = arraysHaveSameContents(localState.allowedAuthMethods, remoteState.allowedAuthMethods) && arraysHaveSameContents(localState.allowedMfaMethods, remoteState.allowedMfaMethods) && localState.isPrimaryAuthAllAllowed === remoteState.isPrimaryAuthAllAllowed && localState.isMfaPolicyRequiredForAll === remoteState.isMfaPolicyRequiredForAll && localState.isSecondaryAuthAllAllowed === remoteState.isSecondaryAuthAllAllowed;
        const allowPrimaryAuth = !localState.isPrimaryAuthAllAllowed && !!localState.allowedAuthMethods && localState.allowedAuthMethods.length === 0;
        const allowSecondaryAuth = !localState.isSecondaryAuthAllAllowed && localState.allowedMfaMethods && localState.allowedMfaMethods.length === 0;
        return isDeepEqual || allowPrimaryAuth || allowSecondaryAuth;
    }, [
        remoteState,
        localState
    ]);
    return /*#__PURE__*/ React__default.createElement(SettingsContainer, {
        title: "Authentication settings",
        hasCTA: canSetAllowedAuthMethods || canSetMfaPolicy || canSetAllowedMfaMethods,
        onSave: handleSave,
        useBlockNavigation: useBlockNavigation,
        editing: editing,
        setEditing: handleSetEditing,
        disableSave: disableSave,
        onCancel: handleCancel
    }, /*#__PURE__*/ React__default.createElement(OrgSettingsAuthenticationSettingsBody, {
        canSetAllowedAuthMethods: canSetAllowedAuthMethods,
        canSetMfaPolicy: canSetMfaPolicy,
        canSetAllowedMfaMethods: canSetAllowedMfaMethods,
        localState: localState,
        setLocalState: setLocalState,
        remoteState: remoteState,
        orgConfigAuthMethods: orgConfigAuthMethods,
        orgConfigMfaMethods: orgConfigMfaMethods,
        mfaPolicyConfig: mfaPolicyConfig
    }));
};

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