import Add from '../../../../../node_modules/@mui/icons-material/esm/Add.mjs';
import React__default, { useMemo } from 'react';
import { isTruthy } from '../../utils/isTruthy.mjs';
import { Autocomplete } from '../components/Autocomplete.mjs';
import { Button } from '../components/Button.mjs';
import { FlexBox } from '../shared/components/FlexBox.mjs';
import { PageLoadingIndicator } from '../components/PageLoadingIndicator.mjs';
import { Select } from '../components/Select.mjs';
import { SettingsContainer } from '../components/SettingsContainer.mjs';
import { Table } from '../components/Table.mjs';
import { TagList } from '../components/TagList.mjs';
import { Typography } from '../components/Typography.mjs';
import { arraysHaveSameContents } from '../utils/arraysHaveSameContents.mjs';
import { useFormState } from '../utils/useFormState.mjs';
import { useMutateScimConnectionRoleAssignments } from '../utils/useMutateScimConnection.mjs';
import { useRbac } from '../utils/useRbac.mjs';
import { useRoleAutocomplete } from '../utils/useRoleAutocomplete.mjs';
import { useRoleDisplayInfo } from '../utils/useRoleDisplayInfo.mjs';
import { useScimConnectionGroups } from '../utils/useScimConnectionGroups.mjs';

const RoleAssignmentsSection$1 = ({ connection, useBlockNavigation })=>{
    const { data: scimConnectionGroups, isLoading: isLoadingScimGroups } = useScimConnectionGroups({
        shouldFetch: true
    });
    const { data: canGetOrgCustomRoles } = useRbac('stytch.custom-org-roles', 'get');
    const { mutate: mutateScimConnection } = useMutateScimConnectionRoleAssignments();
    const { getRoleIdDisplayName } = useRoleDisplayInfo(canGetOrgCustomRoles ?? false);
    const scimGroups = useMemo(()=>scimConnectionGroups?.scim_groups ?? [], [
        scimConnectionGroups
    ]);
    const scimRoleAssignments = connection?.scim_group_implicit_role_assignments;
    const { groupIdToName, filteredGroupIdToRoles } = useMemo(()=>{
        const groupIdToNameMap = scimGroups.reduce((acc, val)=>{
            acc[val.group_id] = val.group_name;
            return acc;
        }, {});
        const groupIdToRolesMap = Object.keys(groupIdToNameMap).reduce((acc, groupId)=>{
            const scimRoleAssignment = scimRoleAssignments.find((roleAssignment)=>roleAssignment.group_id === groupId);
            if (!scimRoleAssignment) return acc;
            if (!acc[groupId]) {
                acc[groupId] = [];
            }
            acc[groupId].push(scimRoleAssignment.role_id);
            return acc;
        }, {});
        return {
            groupIdToName: groupIdToNameMap,
            // Filter out groups with no roles assigned
            filteredGroupIdToRoles: Object.fromEntries(Object.entries(groupIdToRolesMap).filter(([, roles])=>roles.length > 0))
        };
    }, [
        scimGroups,
        scimRoleAssignments
    ]);
    const remoteState = useMemo(()=>({
            groupRoles: Object.entries(filteredGroupIdToRoles).map(([groupId, roles])=>({
                    groupId,
                    roles
                }))
        }), [
        filteredGroupIdToRoles
    ]);
    const { localState, setLocalState, editing, handleSetEditing } = useFormState({
        remoteState
    });
    const { groupRoles } = editing ? localState : remoteState;
    const itemRenderer = [
        {
            title: 'Group',
            getValue: ({ groupId })=>{
                return /*#__PURE__*/ React__default.createElement(Typography, {
                    variant: "body2",
                    color: "secondary"
                }, groupId ? groupIdToName[groupId] : '');
            },
            width: 300
        },
        {
            title: 'Role',
            getValue: ({ roles })=>{
                return /*#__PURE__*/ React__default.createElement(TagList, {
                    tags: roles.map((role)=>getRoleIdDisplayName(role))
                });
            }
        }
    ];
    const roleAutocompleteProps = useRoleAutocomplete({
        includeOrgRoles: canGetOrgCustomRoles ?? false
    });
    const groupIdsWithRoleAssignments = new Set(groupRoles.map(({ groupId })=>groupId));
    const findAvailableGroupIds = (currentId)=>Object.keys(groupIdToName).filter((groupId)=>!groupIdsWithRoleAssignments.has(groupId) || groupId === currentId);
    // Find the groupIds that do not have any roles assigned to them.
    const availableGroupIds = findAvailableGroupIds(undefined);
    const handleOnChange = ({ groupId: currentGroupId, updatedGroupId, updatedRoles })=>{
        setLocalState((prevState)=>({
                groupRoles: prevState.groupRoles.map((value)=>{
                    if (value.groupId !== currentGroupId) {
                        return value;
                    }
                    return {
                        groupId: updatedGroupId ?? value.groupId,
                        roles: updatedRoles ?? value.roles
                    };
                })
            }));
    };
    const disableSave = arraysHaveSameContents(localState.groupRoles, remoteState.groupRoles);
    const disableAdd = (localState.groupRoles.length > 0 ? localState.groupRoles[localState.groupRoles.length - 1].groupId === undefined : false) || !availableGroupIds.length;
    const handleSave = async ()=>{
        await mutateScimConnection({
            connection_id: connection.connection_id,
            scim_group_implicit_role_assignments: localState.groupRoles.flatMap(({ groupId, roles })=>{
                return roles.map((role)=>{
                    if (groupId) {
                        return {
                            group_id: groupId,
                            role_id: role
                        };
                    }
                }).filter(isTruthy);
            })
        });
    };
    if (isLoadingScimGroups) {
        return /*#__PURE__*/ React__default.createElement(PageLoadingIndicator, null);
    }
    return /*#__PURE__*/ React__default.createElement(SettingsContainer, {
        title: "Role Assignments",
        hasCTA: Object.keys(groupIdToName).length > 0,
        onSave: handleSave,
        useBlockNavigation: useBlockNavigation,
        editing: editing,
        disableSave: disableSave,
        setEditing: handleSetEditing
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "h4"
    }, "Group Roles"), editing ? /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 2
    }, localState.groupRoles.length > 0 ? /*#__PURE__*/ React__default.createElement("div", null, groupRoles.map(({ groupId, roles }, index)=>{
        const groupNameSelectItems = findAvailableGroupIds(groupId).map((groupId)=>{
            return {
                value: groupId,
                label: groupIdToName[groupId]
            };
        });
        return /*#__PURE__*/ React__default.createElement(FlexBox, {
            flexDirection: "row",
            gap: 2,
            key: index,
            alignItems: "center"
        }, /*#__PURE__*/ React__default.createElement(Select, {
            labelColor: "secondary",
            width: 300,
            label: "Group name",
            selectItems: groupNameSelectItems,
            placeholder: "Select Group Name",
            value: groupId,
            onChange: (value)=>handleOnChange({
                    groupId,
                    updatedGroupId: value,
                    updatedRoles: undefined
                })
        }), /*#__PURE__*/ React__default.createElement(Autocomplete, {
            ...roleAutocompleteProps,
            label: "Group Role",
            fullWidth: true,
            value: roles,
            onChange: (value)=>handleOnChange({
                    groupId,
                    updatedGroupId: undefined,
                    updatedRoles: value
                })
        }));
    })) : /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body2"
    }, "No roles assigned."), /*#__PURE__*/ React__default.createElement(Button, {
        disabled: disableAdd,
        startIcon: /*#__PURE__*/ React__default.createElement(Add, null),
        variant: "text",
        onClick: ()=>{
            setLocalState(()=>({
                    groupRoles: [
                        ...groupRoles,
                        {
                            groupId: undefined,
                            roles: []
                        }
                    ]
                }));
        }
    }, "Add group roles")) : groupRoles.length > 0 ? /*#__PURE__*/ React__default.createElement(Table, {
        titleVariant: "caption",
        itemRenderer: itemRenderer,
        items: groupRoles,
        rowKeyExtractor: ({ groupId })=>groupId ?? '',
        disableBottomBorder: true
    }) : /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body2"
    }, "No roles assigned."));
};

export { RoleAssignmentsSection$1 as RoleAssignmentsSection };
//# sourceMappingURL=SCIMConnectionRoleAssignmentsSection.mjs.map
