import React__default, { useState, useCallback } from 'react';
import '../../../../../_virtual/index2.mjs';
import { useSWRConfig } from '../../../../../node_modules/swr/_internal/dist/index.mjs';
import { extractErrorMessage } from '../../utils/extractErrorMessage.mjs';
import { Button } from '../components/Button.mjs';
import { FlexBox } from '../shared/components/FlexBox.mjs';
import { Input } from '../components/Input.mjs';
import { Select } from '../components/Select.mjs';
import { useToast } from '../shared/components/Toast.mjs';
import { Typography } from '../components/Typography.mjs';
import { useRevalidateConnectionList } from '../utils/useRevalidateConnectionList.mjs';
import { useStytchClient } from '../utils/useStytchClient.mjs';
import { idpOptions, idpSelectItems } from './IdpSelect.mjs';
import { useSsoRouterController } from './SSORouter.mjs';
import ChevronLeft from '../../../../../node_modules/@mui/icons-material/esm/ChevronLeft.mjs';

const SSONewConnectionScreen = ()=>{
    const { navigate } = useSsoRouterController();
    const { openToast } = useToast();
    const [displayName, setDisplayName] = useState('');
    const [isExternalConnection, setIsExternalConnection] = useState(false);
    const [idp, setIdp] = useState();
    const [sourceOrgId, setSourceOrgId] = useState('');
    const [sourceConnectionId, setSourceConnectionId] = useState('');
    const isNewConnectionReadyToCreate = !!idp;
    const isExternalConnectionReadyToCreate = sourceOrgId && sourceConnectionId;
    const isReadyToCreate = displayName && (isExternalConnection ? isExternalConnectionReadyToCreate : isNewConnectionReadyToCreate);
    const client = useStytchClient();
    const { mutate } = useSWRConfig();
    const revalidateConnectionList = useRevalidateConnectionList();
    const handleSubmit = useCallback(async (e)=>{
        e.preventDefault();
        if (isExternalConnection) {
            if (!isExternalConnectionReadyToCreate) {
                return;
            }
            const response = await mutate('sso_create', async ()=>{
                try {
                    return await client.sso.external.createConnection({
                        display_name: displayName,
                        external_organization_id: sourceOrgId,
                        external_connection_id: sourceConnectionId
                    });
                } catch (e) {
                    const message = extractErrorMessage(e);
                    openToast({
                        text: message || 'Unable to create connection',
                        type: 'error'
                    });
                }
            });
            if (response) {
                await revalidateConnectionList();
                navigate({
                    screen: 'connectionsList'
                });
            }
        } else {
            if (!isNewConnectionReadyToCreate) {
                return;
            }
            const { idpName, type } = idpOptions[idp];
            const response = await mutate('sso_create', async ()=>{
                const params = {
                    display_name: displayName,
                    identity_provider: idpName
                };
                try {
                    if (type === 'oidc') {
                        return await client.sso.oidc.createConnection(params);
                    }
                    if (type === 'saml') {
                        return await client.sso.saml.createConnection(params);
                    }
                } catch (e) {
                    const message = extractErrorMessage(e);
                    openToast({
                        text: message || 'Unable to create connection',
                        type: 'error'
                    });
                }
            });
            if (response) {
                await revalidateConnectionList();
                navigate({
                    screen: 'newConnectionConfigure',
                    params: {
                        connection: {
                            ...response.connection,
                            connectionType: type
                        }
                    }
                });
            }
        }
    }, [
        isExternalConnection,
        isExternalConnectionReadyToCreate,
        mutate,
        client.sso.external,
        client.sso.oidc,
        client.sso.saml,
        displayName,
        sourceOrgId,
        sourceConnectionId,
        openToast,
        revalidateConnectionList,
        navigate,
        isNewConnectionReadyToCreate,
        idp
    ]);
    return /*#__PURE__*/ React__default.createElement("form", {
        onSubmit: handleSubmit
    }, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 3
    }, /*#__PURE__*/ React__default.createElement(Button, {
        variant: "ghost",
        compact: true,
        onClick: ()=>{
            navigate({
                screen: 'connectionsList'
            });
        },
        startIcon: /*#__PURE__*/ React__default.createElement(ChevronLeft, null)
    }, "Back to all SSO connections"), /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "h2"
    }, "New SSO Connection"), /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 1
    }, /*#__PURE__*/ React__default.createElement(Typography, null, "Set a display name for your connection."), /*#__PURE__*/ React__default.createElement(Input, {
        placeholder: "Text",
        value: displayName,
        onChange: setDisplayName,
        caption: "You will be able to edit this again in the future."
    })), /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 1
    }, isExternalConnection ? /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, /*#__PURE__*/ React__default.createElement(Typography, null, "Add an existing SSO connection from another organization by inputting the Source Organization ID and desired SSO Connection ID."), /*#__PURE__*/ React__default.createElement(FlexBox, {
        gap: 1
    }, /*#__PURE__*/ React__default.createElement(Input, {
        label: "Source Organization ID",
        placeholder: "organization-live-12345678-9012-3456-7890-123456789012",
        value: sourceOrgId,
        onChange: setSourceOrgId
    }), /*#__PURE__*/ React__default.createElement(Input, {
        label: "Source Connection ID",
        placeholder: "abcd-connection-live-12345678-9012-3456-7890-123456789012",
        value: sourceConnectionId,
        onChange: setSourceConnectionId
    }))) : /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, /*#__PURE__*/ React__default.createElement(Typography, null, "Select your identity provider or choose to configure a custom SAML / OIDC connection."), /*#__PURE__*/ React__default.createElement(Select, {
        placeholder: "Select",
        selectItems: idpSelectItems,
        value: idp,
        onChange: setIdp
    })), /*#__PURE__*/ React__default.createElement(Button, {
        variant: "ghost",
        onClick: ()=>setIsExternalConnection(!isExternalConnection)
    }, isExternalConnection ? 'Add connection by IdP' : 'Add an external connection')), /*#__PURE__*/ React__default.createElement(Typography, null, "Once you click “Create” the SSO connection will be created. If you need to change the connection type after this, you will need to start over."), /*#__PURE__*/ React__default.createElement(FlexBox, {
        justifyContent: "space-between"
    }, /*#__PURE__*/ React__default.createElement(Button, {
        variant: "ghost",
        onClick: ()=>{
            navigate({
                screen: 'connectionsList'
            });
        }
    }, "Cancel"), /*#__PURE__*/ React__default.createElement(Button, {
        type: "submit",
        disabled: !isReadyToCreate
    }, "Create"))));
};

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