import React__default, { useMemo, useState, useCallback } from 'react';
import { Button } from '../components/Button.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 { Select } from '../components/Select.mjs';
import { Typography } from '../components/Typography.mjs';
import { collator } from '../utils/collator.mjs';
import { useModalState } from '../shared/components/Modal.mjs';
import Add from '../../../../../node_modules/@mui/icons-material/esm/Add.mjs';

const nameKeys = new Set([
    'full_name',
    'first_name',
    'last_name'
]);
const requiredKeys = new Set([
    ...nameKeys,
    'email'
]);
const attributeMappingItemRenderer = [
    {
        title: 'Key',
        getValue: ({ key })=>{
            const isRequiredKey = requiredKeys.has(key);
            const label = key;
            return /*#__PURE__*/ React__default.createElement(Typography, {
                variant: "body2"
            }, label, isRequiredKey && /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, ' ', /*#__PURE__*/ React__default.createElement(Typography, {
                component: "span",
                color: "error"
            }, "*")));
        }
    },
    {
        title: 'Value',
        getValue: ({ value })=>/*#__PURE__*/ React__default.createElement(Typography, {
                variant: "body2"
            }, value)
    }
];
const attributeMappingKeyExtractor = ({ key })=>key;
const AttributeMappingTable = ({ editing, localState, remoteState, setLocalState })=>{
    const { attributeMapping } = editing ? localState : remoteState;
    const attributeMappingItems = useMemo(()=>Object.entries(attributeMapping).map(([key, value])=>({
                key,
                value
            })).sort((a, b)=>collator.compare(a.key, b.key)), [
        attributeMapping
    ]);
    const [pendingAttributeMapping, setPendingAttributeMapping] = useState([
        [
            '',
            ''
        ]
    ]);
    const [editMode, setEditMode] = useState('key');
    const [editedAttributeMappingKey, setEditedAttributeMappingKey] = useState('');
    const [editedAttributeMappingValue, setEditedAttributeMappingValue] = useState('');
    const [editedAttributeMappingLastNameValue, setEditedAttributeMappingLastNameValue] = useState('');
    const editAttributeMappingModalProps = useModalState(()=>{
        const editedMapping = editMode === 'name' && editedAttributeMappingKey === 'first_name' ? {
            first_name: editedAttributeMappingValue,
            last_name: editedAttributeMappingLastNameValue
        } : {
            [editedAttributeMappingKey]: editedAttributeMappingValue
        };
        setLocalState((state)=>{
            const mergedMapping = {
                ...state.attributeMapping,
                ...editedMapping
            };
            if (editMode === 'name') {
                if (editedAttributeMappingKey === 'full_name') {
                    delete mergedMapping.first_name;
                    delete mergedMapping.last_name;
                }
                if (editedAttributeMappingKey === 'first_name') {
                    delete mergedMapping.full_name;
                }
            }
            return {
                ...state,
                attributeMapping: mergedMapping
            };
        });
    });
    const hasFirstAndLastNameKeys = !!(attributeMapping.first_name && attributeMapping.last_name);
    const hasFullNameKey = !!attributeMapping.full_name;
    const handleEditAttributeMapping = useCallback((key)=>{
        if (key === 'full_name' && !attributeMapping.first_name && !attributeMapping.last_name || (key === 'first_name' || key === 'last_name') && !hasFullNameKey) {
            setEditMode('name');
            const effectiveKey = key === 'full_name' ? 'full_name' : 'first_name';
            setEditedAttributeMappingKey(effectiveKey);
            setEditedAttributeMappingValue(attributeMapping[effectiveKey] ?? '');
            setEditedAttributeMappingLastNameValue(attributeMapping.last_name ?? '');
        } else {
            setEditMode('key');
            setEditedAttributeMappingKey(key);
            setEditedAttributeMappingValue(attributeMapping[key] ?? '');
        }
        editAttributeMappingModalProps.open();
    }, [
        attributeMapping,
        editAttributeMappingModalProps,
        hasFullNameKey
    ]);
    const deleteAttributeMapping = useCallback((key)=>{
        setLocalState((state)=>{
            const { [key]: _, ...rest } = state.attributeMapping;
            return {
                ...state,
                attributeMapping: rest
            };
        });
    }, [
        setLocalState
    ]);
    const deleteAttributeMappingModalProps = useModalState(()=>{
        if (pendingDeleteAttributeMappingKey) {
            deleteAttributeMapping(pendingDeleteAttributeMappingKey);
        }
    });
    const [pendingDeleteAttributeMappingKey, setPendingDeleteAttributeMappingKey] = useState();
    const handleRequestDeleteAttributeMapping = useCallback((key)=>{
        if (key !== 'groups') {
            deleteAttributeMapping(key);
        } else {
            setPendingDeleteAttributeMappingKey(key);
            deleteAttributeMappingModalProps.open();
        }
    }, [
        deleteAttributeMapping,
        deleteAttributeMappingModalProps
    ]);
    return /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, /*#__PURE__*/ React__default.createElement(Modal, {
        ...editAttributeMappingModalProps,
        title: "Edit custom mapping",
        confirmButtonText: "Save"
    }, /*#__PURE__*/ React__default.createElement(FlexBox, {
        flexDirection: "column",
        gap: 1
    }, editMode === 'name' ? /*#__PURE__*/ React__default.createElement(Select, {
        selectItems: [
            {
                label: 'Full Name',
                value: 'full_name'
            },
            {
                label: 'First Name, Last Name',
                value: 'first_last_name'
            }
        ],
        fullWidth: true,
        caption: "You can change the format of the key.",
        value: editedAttributeMappingKey === 'full_name' ? 'full_name' : 'first_last_name',
        onChange: (value)=>{
            setEditedAttributeMappingKey(value === 'full_name' ? 'full_name' : 'first_name');
        }
    }) : /*#__PURE__*/ React__default.createElement(Input, {
        label: "Key",
        fullWidth: true,
        value: editedAttributeMappingKey,
        onChange: setEditedAttributeMappingKey
    }), editMode === 'name' && (editedAttributeMappingKey === 'first_name' || editedAttributeMappingKey === 'last_name') ? /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, /*#__PURE__*/ React__default.createElement(FlexBox, {
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(Input, {
        label: "First Name",
        fullWidth: true,
        value: editedAttributeMappingValue,
        onChange: setEditedAttributeMappingValue
    }), /*#__PURE__*/ React__default.createElement(Input, {
        label: "Last Name",
        fullWidth: true,
        value: editedAttributeMappingLastNameValue,
        onChange: setEditedAttributeMappingLastNameValue
    }))) : /*#__PURE__*/ React__default.createElement(Input, {
        label: "Value",
        fullWidth: true,
        value: editedAttributeMappingValue,
        onChange: setEditedAttributeMappingValue
    }))), /*#__PURE__*/ React__default.createElement(Modal, {
        ...deleteAttributeMappingModalProps,
        title: "Delete mapping?",
        confirmButtonText: "Delete",
        warning: true
    }, /*#__PURE__*/ React__default.createElement(Typography, null, "Deleting the Groups attribute mapping will also disable any Group Role assignments you have added above. They will not be deleted, but you must add a Groups mapping to make edits.")), /*#__PURE__*/ React__default.createElement(ListEditor, {
        items: attributeMappingItems,
        itemRenderer: attributeMappingItemRenderer,
        rowKeyExtractor: attributeMappingKeyExtractor,
        addModalProps: {
            confirm: ()=>{
                setLocalState((state)=>{
                    return {
                        ...state,
                        attributeMapping: {
                            ...state.attributeMapping,
                            ...Object.fromEntries(pendingAttributeMapping.filter(([key, value])=>key && value && !state.attributeMapping[key]))
                        }
                    };
                });
                return Promise.resolve();
            },
            title: 'Add custom mapping',
            content: /*#__PURE__*/ React__default.createElement(FlexBox, {
                flexDirection: "column",
                gap: 1
            }, pendingAttributeMapping.map(([key, value], i)=>/*#__PURE__*/ React__default.createElement(FlexBox, {
                    gap: 1,
                    key: i
                }, /*#__PURE__*/ React__default.createElement(Input, {
                    label: "Key",
                    fullWidth: true,
                    value: key,
                    onChange: (value)=>{
                        setPendingAttributeMapping((state)=>state.map((item, index)=>index === i ? [
                                    value,
                                    item[1]
                                ] : item));
                    }
                }), /*#__PURE__*/ React__default.createElement(Input, {
                    label: "Value",
                    fullWidth: true,
                    value: value,
                    onChange: (value)=>{
                        setPendingAttributeMapping((state)=>state.map((item, index)=>index === i ? [
                                    item[0],
                                    value
                                ] : item));
                    }
                }))), /*#__PURE__*/ React__default.createElement(Button, {
                variant: "text",
                startIcon: /*#__PURE__*/ React__default.createElement(Add, null),
                fullWidth: true,
                onClick: ()=>{
                    setPendingAttributeMapping((state)=>[
                            ...state,
                            [
                                '',
                                ''
                            ]
                        ]);
                }
            }, "Add custom mapping"))
        },
        hideAddButton: !editing,
        getItemActionProps: editing ? (item)=>({
                action: // Only allow editing email if its value is not expected
                item.key === 'email' && item.value === 'NameID' ? undefined : {
                    text: 'Edit',
                    onClick: ()=>{
                        handleEditAttributeMapping(item.key);
                    }
                },
                warningAction: // Never allow deleting email; allow deleting name-related fields only if they are superfluous
                item.key === 'email' || nameKeys.has(item.key) && !(hasFirstAndLastNameKeys && hasFullNameKey) ? undefined : {
                    text: 'Delete',
                    onClick: ()=>{
                        handleRequestDeleteAttributeMapping(item.key);
                    }
                }
            }) : undefined
    }));
};

export { AttributeMappingTable, attributeMappingItemRenderer, attributeMappingKeyExtractor, nameKeys, requiredKeys };
//# sourceMappingURL=AttributeMappingTable.mjs.map
