import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useContext, useEffect, useMemo, useState } from 'react';
import { useThemeProps } from '@mui/system';
import { styled } from '@mui/material/styles';
import { Avatar, Box, Button, Chip, Icon, IconButton, InputAdornment, TextField, Typography } from '@mui/material';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import { SCUserContext, useSCFetchGroup } from '@selfcommunity/react-core';
import classNames from 'classnames';
import BaseDialog from '../../shared/BaseDialog';
import { LoadingButton } from '@mui/lab';
import { GroupService } from '@selfcommunity/api-services';
import Autocomplete from '@mui/material/Autocomplete';
import User from '../User';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { Logger } from '@selfcommunity/utils';
import { SCGroupEventType, SCTopicType } from '../../constants/PubSub';
import PubSub from 'pubsub-js';
const messages = defineMessages({
    placeholder: {
        id: 'ui.groupInviteButton.searchBar.placeholder',
        defaultMessage: 'ui.groupInviteButton.searchBar.placeholder'
    }
});
const PREFIX = 'SCGroupInviteButton';
const classes = {
    root: `${PREFIX}-root`,
    dialogRoot: `${PREFIX}-dialog-root`,
    dialogTitle: `${PREFIX}-dialog-title`,
    dialogContent: `${PREFIX}-dialog-content`,
    autocomplete: `${PREFIX}-autocomplete`,
    icon: `${PREFIX}-icon`,
    input: `${PREFIX}-input`,
    clear: `${PREFIX}-clear`,
    invitedBox: `${PREFIX}-invited-box`,
    suggested: `${PREFIX}-suggested`
};
const Root = styled(Button, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({}));
const DialogRoot = styled(BaseDialog, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.dialogRoot
})(({ theme }) => ({}));
/**
 *> API documentation for the Community-JS Group Invite Button component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {SCGroupInviteButton} from '@selfcommunity/react-ui';
 ```

 #### Component Name
 The name `SCGroupInviteButton` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCGroupInviteButton-root|Styles applied to the root element.|
 |dialogRoot|.SCGroupInviteButton-dialog-root|Styles applied to the dialog root.|
 |dialogTitle|.SCGroupInviteButton-dialog-title|Styles applied to the dialog title element.|
 |dialogContent|.SCGroupInviteButton-dialog-content|Styles applied to the dialog content.|
 |autocomplete|.SCGroupInviteButton-autocomplete|Styles applied to the autocomplete element.|
 |icon|.SCGroupInviteButton-icon|Styles applied to the autocomplete icon element.|
 |input|.SCGroupInviteButton-input|Styles applied to the autocomplete input element.|
 |clear|.SCGroupInviteButton-clear|Styles applied to the autocomplete clear icon element.|
 |invitedBox|.SCGroupInviteButton-invited-box|Styles applied to the invited users box.|
 |suggested|.SCGroupInviteButton-suggested|Styles applied to the suggested users box.|

 * @param inProps
 */
export default function GroupInviteButton(inProps) {
    var _a;
    //PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, group, groupId, handleInvitations = null } = props, rest = __rest(props, ["className", "group", "groupId", "handleInvitations"]);
    // CONTEXT
    const scUserContext = useContext(SCUserContext);
    // STATE
    const [open, setOpen] = useState(false);
    const [isSending, setIsSending] = useState(false);
    const [value, setValue] = useState('');
    const [suggested, setSuggested] = useState([]);
    const [list, setList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [invited, setInvited] = useState([]);
    /**
     * Notify UI when a member is invited to a group
     * @param group
     * @param usersInvited
     */
    function notifyChanges(group, usersInvited) {
        if (group && usersInvited) {
            PubSub.publish(`${SCTopicType.GROUP}.${SCGroupEventType.INVITE_MEMBER}`, usersInvited);
        }
    }
    function convertToInvitedUsersObject(data) {
        const invite_users = {};
        data.forEach((user, index) => {
            invite_users[`invite_users[${index}]`] = user.id;
        });
        return invite_users;
    }
    /**
     * Memoized users invited ids
     */
    const ids = useMemo(() => {
        if (invited) {
            return invited.map((u) => {
                return parseInt(u.id, 10);
            });
        }
        return [invited];
    }, [invited]);
    // HOOKS
    const { scGroup } = useSCFetchGroup({ id: groupId, group });
    const isGroupAdmin = useMemo(() => { var _a; return scUserContext.user && ((_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id) === scUserContext.user.id; }, [scUserContext.user, (_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id]);
    // INTL
    const intl = useIntl();
    function fetchResults() {
        setLoading(true);
        GroupService.getGroupSuggestedUsers(scGroup === null || scGroup === void 0 ? void 0 : scGroup.id, value)
            .then((data) => {
            setLoading(false);
            setSuggested(data.results);
        })
            .catch((error) => {
            setLoading(false);
            Logger.error(SCOPE_SC_UI, error);
        });
    }
    function fetchGeneralResults() {
        setLoading(true);
        GroupService.getGroupsSuggestedUsers(value)
            .then((data) => {
            setLoading(false);
            setSuggested(data.results);
        })
            .catch((error) => {
            setLoading(false);
            Logger.error(SCOPE_SC_UI, error);
        });
    }
    useEffect(() => {
        if (scGroup === null || scGroup === void 0 ? void 0 : scGroup.id) {
            GroupService.getGroupSuggestedUsers(scGroup === null || scGroup === void 0 ? void 0 : scGroup.id, value).then((data) => {
                setLoading(false);
                setList(data.results);
            });
        }
        else {
            GroupService.getGroupsSuggestedUsers(value).then((data) => {
                setLoading(false);
                setList(data.results);
            });
        }
    }, [scGroup === null || scGroup === void 0 ? void 0 : scGroup.id]);
    /**
     * If a value is entered in new message field, it fetches user suggested
     */
    useEffect(() => {
        if (scGroup) {
            fetchResults();
        }
        else {
            fetchGeneralResults();
        }
    }, [value, scGroup]);
    /**
     * Handles dialog close
     */
    const handleClose = () => {
        setOpen((p) => !p);
    };
    /**
     * Handles invitation sending
     */
    const handleSendInvitations = () => {
        if (handleInvitations) {
            handleInvitations(convertToInvitedUsersObject(invited));
            setOpen(false);
        }
        else {
            const data = { users: ids };
            setIsSending(true);
            GroupService.inviteOrAcceptGroupRequest(scGroup.id, data)
                .then(() => {
                setIsSending(false);
                setOpen(false);
                setInvited([]);
                notifyChanges(scGroup, invited);
            })
                .catch((error) => {
                setOpen(false);
                setLoading(false);
                Logger.error(SCOPE_SC_UI, error);
            });
        }
    };
    // Autocomplete Handlers
    const handleInputChange = (event, value, reason) => {
        switch (reason) {
            case 'input':
                setValue(value);
                !value && setSuggested([]);
                break;
            case 'reset':
                setValue(value);
                break;
        }
    };
    const handleChange = (event, value, reason, details) => {
        event.preventDefault();
        event.stopPropagation();
        switch (reason) {
            case 'selectOption':
                setInvited(value);
                setList((prev) => prev.filter((u) => u.id !== details.option.id));
                break;
            case 'removeOption':
                setInvited(value);
                setList((prev) => [...prev, details.option]);
                break;
        }
        return false;
    };
    const handleUserInvite = (user) => {
        setInvited((prev) => [...prev, user]);
        setList((prev) => prev.filter((u) => u.id !== user.id));
    };
    const handleDelete = (option) => {
        setInvited(invited.filter((v) => v !== option));
        setList((prev) => [...prev, option]);
    };
    const filterOptions = (options, { inputValue }) => {
        return options.filter((option) => {
            const usernameMatch = option.username.toLowerCase().includes(inputValue.toLowerCase());
            const nameMatch = option.real_name.toLowerCase().includes(inputValue.toLowerCase());
            return usernameMatch || nameMatch;
        });
    };
    /**
     * If in group edit mode and logged-in user is not also the group manager, the component is hidden.
    //  */
    if (group && !isGroupAdmin) {
        return null;
    }
    /**
     * Renders root object
     */
    return (_jsxs(React.Fragment, { children: [_jsx(Root, Object.assign({ className: classNames(classes.root, className), onClick: handleClose, variant: scGroup ? 'contained' : 'outlined', color: scGroup ? 'secondary' : 'inherit', startIcon: _jsx(Icon, { children: "add" }) }, rest, { children: _jsx(FormattedMessage, { id: "ui.groupInviteButton", defaultMessage: "ui.groupInviteButton" }) })), open && (_jsx(DialogRoot, Object.assign({ DialogContentProps: { dividers: false }, open: true, className: classes.dialogRoot, title: _jsxs(_Fragment, { children: [_jsx(IconButton, Object.assign({ onClick: handleClose }, { children: _jsx(Icon, { children: "arrow_back" }) })), _jsx(Typography, Object.assign({ className: classes.dialogTitle }, { children: _jsx(FormattedMessage, { id: "ui.groupInviteButton.dialog.title", defaultMessage: "ui.groupInviteButton.dialog.title" }) })), _jsx(LoadingButton, Object.assign({ size: "small", color: "secondary", variant: "contained", onClick: handleSendInvitations, loading: isSending, disabled: !invited.length }, { children: _jsx(FormattedMessage, { id: "ui.groupInviteButton.dialog.button.end", defaultMessage: "ui.groupInviteButton.dialog.button.end" }) }))] }) }, { children: _jsxs(Box, Object.assign({ className: classes.dialogContent }, { children: [_jsx(Autocomplete, { className: classes.autocomplete, loading: loading, size: "small", multiple: true, freeSolo: true, disableClearable: true, options: suggested, onChange: handleChange, onInputChange: handleInputChange, inputValue: value, filterOptions: filterOptions, value: invited, getOptionLabel: (option) => (option ? option.username : '...'), isOptionEqualToValue: (option, value) => (option ? value.id === option.id : false), renderTags: () => null, renderOption: (props, option) => (_jsxs(Box, Object.assign({ component: "li" }, props, { children: [_jsx(Avatar, { alt: option.username, src: option.avatar }), _jsx(Typography, Object.assign({ ml: 1 }, { children: option.username }))] }))), renderInput: (params) => (_jsx(TextField, Object.assign({}, params, { variant: "outlined", placeholder: `${intl.formatMessage(messages.placeholder)}`, InputProps: Object.assign(Object.assign({}, params.InputProps), { className: classes.input, startAdornment: (_jsxs(_Fragment, { children: [_jsx(InputAdornment, Object.assign({ position: "start" }, { children: _jsx(Icon, Object.assign({ className: classes.icon }, { children: "search" })) })), params.InputProps.startAdornment] })) }) }))) }), _jsx(Box, Object.assign({ className: classes.invitedBox }, { children: invited.map((option, index) => (_jsx(Chip, { avatar: _jsx(Avatar, { alt: option.username, src: option.avatar }), label: option.username, onDelete: () => {
                                    handleDelete(option);
                                }, style: { marginRight: 8 } }, index))) })), _jsxs(Box, Object.assign({ className: classes.suggested }, { children: [list.length !== 0 && (_jsx(Typography, Object.assign({ variant: "h4", fontWeight: "bold" }, { children: _jsx(FormattedMessage, { id: "ui.groupInviteButton.dialog.content.list", defaultMessage: "ui.groupInviteButton.dialog.content.list" }) }))), list.slice(0, 5).map((user, index) => (_jsx(User, { elevation: 0, actions: _jsx(_Fragment, {}), user: user, userId: user.id, buttonProps: { onClick: () => handleUserInvite(user) } }, index)))] }))] })) })))] }));
}
