import React__default, { useMemo, useCallback, useState } from 'react';
import { useActionMenu } from '../components/ActionMenu.mjs';
import { Alert } from '../components/Alert.mjs';
import { Button } from '../components/Button.mjs';
import { useDeleteConnection, DeleteConfirmModal } from '../components/DeleteConnection.mjs';
import { FlexBox } from '../shared/components/FlexBox.mjs';
import { PaginatedTable } from '../components/PaginatedTable.mjs';
import { SearchBar } from '../components/SearchBar.mjs';
import { useSetDefaultConnection, SetDefaultConfirmModal } from '../components/SetDefaultConnection.mjs';
import { Tag } from '../components/Tag.mjs';
import { Typography } from '../components/Typography.mjs';
import { getDisplayStatus } from '../utils/getDisplay.mjs';
import { NO_VALUE } from '../utils/noValue.mjs';
import { useAdminPortalConfig } from '../utils/useAdminPortalConfig.mjs';
import { useConnections } from '../utils/useConnections.mjs';
import { useDisplayPagination } from '../utils/useDisplayPagination.mjs';
import { useRbac } from '../utils/useRbac.mjs';
import { getIdpInfo } from './IdpInfo.mjs';
import { useSsoRouterController } from './SSORouter.mjs';
import VisibilityOutlined from '../../../../../node_modules/@mui/icons-material/esm/VisibilityOutlined.mjs';
import EditOutlined from '../../../../../node_modules/@mui/icons-material/esm/EditOutlined.mjs';
import Tune from '../../../../../node_modules/@mui/icons-material/esm/Tune.mjs';
import DeleteOutlined from '../../../../../node_modules/@mui/icons-material/esm/DeleteOutlined.mjs';
import Add from '../../../../../node_modules/@mui/icons-material/esm/Add.mjs';

const itemRenderer = [
    {
        title: 'Display Name',
        getValue: ({ displayName, isDefault })=>{
            return isDefault ? /*#__PURE__*/ React__default.createElement(Typography, {
                variant: "body2"
            }, displayName, " ", /*#__PURE__*/ React__default.createElement(Tag, {
                size: "small"
            }, "Default")) : displayName;
        }
    },
    {
        title: 'IdP',
        getValue: ({ idp, connectionType })=>{
            return idp ? getIdpInfo(idp, connectionType).idp.displayName : NO_VALUE;
        },
        width: 200
    },
    {
        title: 'Status',
        getValue: ({ status })=>getDisplayStatus(status),
        width: 150
    }
];
const useSearchFilter = ({ data, searchKeys })=>{
    const [filterText, setFilterText] = useState('');
    const filteredData = useMemo(()=>{
        if (!filterText) {
            return data;
        }
        const filterTextLower = filterText.toLowerCase();
        return data.filter((item)=>{
            return searchKeys.some((key)=>{
                return String(item[key]).toLowerCase().includes(filterTextLower);
            });
        });
    }, [
        data,
        filterText,
        searchKeys
    ]);
    return {
        filteredData,
        filterText,
        setFilterText
    };
};
const useCanProjectCreateSsoConnection = ()=>{
    const { data } = useAdminPortalConfig({
        shouldFetch: true
    });
    return data?.sso_config.can_create_oidc_connection && data.sso_config.can_create_saml_connection;
};
const getConnectionId = (connection)=>connection.id;
const SSOConnectionsScreen = ()=>{
    const { navigate } = useSsoRouterController();
    const canProjectCreateSsoConnection = useCanProjectCreateSsoConnection();
    const { data: canGetConnection } = useRbac('stytch.sso', 'get');
    const { data: canCreatePermission } = useRbac('stytch.sso', 'create');
    const { data: canDeleteConnection } = useRbac('stytch.sso', 'delete');
    const { data: canUpdateConnection } = useRbac('stytch.sso', 'update');
    const { data: canSetDefaultConnection } = useRbac('stytch.organization', 'update.settings.default-sso-connection');
    const canCreateConnection = canCreatePermission && canProjectCreateSsoConnection;
    const { connections, isLoading } = useConnections(!!canGetConnection);
    const { filterText, setFilterText, filteredData } = useSearchFilter({
        data: connections,
        searchKeys: [
            'displayName'
        ]
    });
    const pagination = useDisplayPagination({
        items: filteredData,
        viewId: 'adminPortalSsoConnections'
    });
    const tableProps = {
        ...pagination,
        onRowClick: (id)=>navigate({
                screen: 'connectionDetails',
                params: {
                    connectionId: id
                }
            })
    };
    const defaultConnectionName = useMemo(()=>connections.find((connection)=>connection.isDefault)?.displayName, [
        connections
    ]);
    const { modalProps: setDefaultModalProps, handleRequestSetDefault: handleSetDefault } = useSetDefaultConnection({
        defaultConnectionName
    });
    const { modalProps: deleteModalProps, handleRequestDelete: handleDelete } = useDeleteConnection();
    const handleEdit = useCallback((connection)=>{
        navigate({
            screen: 'connectionDetails',
            params: {
                connectionId: connection.id
            }
        });
    }, [
        navigate
    ]);
    const handleNewConnectionClick = useCallback(()=>{
        navigate({
            screen: 'newConnection'
        });
    }, [
        navigate
    ]);
    const hasExactlyOneConnection = connections.length === 1;
    const actions = useMemo(()=>[
            {
                key: 'view',
                label: 'View connection',
                icon: /*#__PURE__*/ React__default.createElement(VisibilityOutlined, null),
                onClick: handleEdit,
                isVisible: !canUpdateConnection
            },
            {
                key: 'edit',
                label: 'Edit connection',
                icon: /*#__PURE__*/ React__default.createElement(EditOutlined, null),
                onClick: handleEdit,
                isVisible: !!canUpdateConnection
            },
            {
                key: 'set-default',
                label: 'Set as default',
                icon: /*#__PURE__*/ React__default.createElement(Tune, null),
                onClick: handleSetDefault,
                isVisible: (connection)=>!connection.isDefault && !!canSetDefaultConnection
            },
            {
                key: 'delete',
                label: 'Delete',
                icon: /*#__PURE__*/ React__default.createElement(DeleteOutlined, null),
                onClick: handleDelete,
                isDangerous: true,
                isVisible: (connection)=>(!connection.isDefault || hasExactlyOneConnection) && !!canDeleteConnection
            }
        ], [
        canDeleteConnection,
        canSetDefaultConnection,
        canUpdateConnection,
        handleDelete,
        handleEdit,
        handleSetDefault,
        hasExactlyOneConnection
    ]);
    const { getItemActionProps } = useActionMenu({
        actions,
        idPrefix: 'connection',
        getId: getConnectionId
    });
    return /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 3
    }, canCreatePermission && !canCreateConnection && /*#__PURE__*/ React__default.createElement(Alert, null, "You’ve reached the maximum number of allowed connections. Delete an existing connection in order to add a new one."), /*#__PURE__*/ React__default.createElement(FlexBox, {
        alignItems: "center",
        justifyContent: "space-between"
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "h1"
    }, "SSO Connections"), canCreateConnection && /*#__PURE__*/ React__default.createElement(Button, {
        compact: true,
        variant: "primary",
        startIcon: /*#__PURE__*/ React__default.createElement(Add, null),
        onClick: handleNewConnectionClick
    }, "New connection")), /*#__PURE__*/ React__default.createElement(SearchBar, {
        placeholder: "Search",
        value: filterText,
        onChange: setFilterText
    }), /*#__PURE__*/ React__default.createElement(PaginatedTable, {
        ...tableProps,
        itemRenderer: itemRenderer,
        isLoading: isLoading,
        titleVariant: "h4",
        getItemActionProps: getItemActionProps
    })), /*#__PURE__*/ React__default.createElement(SetDefaultConfirmModal, setDefaultModalProps), /*#__PURE__*/ React__default.createElement(DeleteConfirmModal, deleteModalProps));
};

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