import { __rest } from "tslib";
import { jsx as _jsx } from "react/jsx-runtime";
import { useContext, useEffect, useState } from 'react';
import { styled } from '@mui/material/styles';
import { SCConnectionStatus } from '@selfcommunity/types';
import classNames from 'classnames';
import { useThemeProps } from '@mui/system';
import { useSnackbar } from 'notistack';
import { FormattedMessage } from 'react-intl';
import { LoadingButton } from '@mui/lab';
import { Logger } from '@selfcommunity/utils';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { catchUnauthorizedActionByBlockedUser } from '../../utils/errors';
import { SCUserContext, UserUtils, useSCContext, useSCFetchUser } from '@selfcommunity/react-core';
const PREFIX = 'SCFriendshipUserButton';
const classes = {
    root: `${PREFIX}-root`
};
const Root = styled(LoadingButton, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(() => ({}));
// TODO: fix component
/**
 * > API documentation for the Community-JS Friendship User Button component. Learn about the available props and the CSS API.

 #### Import

 ```jsx
 import {FriendshipUserButton} from '@selfcommunity/react-ui';
 ```

 #### Component Name

 The name `SCFriendshipUserButton` can be used when providing style overrides in the theme.


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCFriendshipUserButton-root|Styles applied to the root element.|

 * @param inProps
 */
export default function FriendshipUserButton(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, userId, user } = props, rest = __rest(props, ["className", "userId", "user"]);
    // CONTEXT
    const scContext = useSCContext();
    const scUserContext = useContext(SCUserContext);
    const scConnectionsManager = scUserContext.managers.connections;
    const { enqueueSnackbar } = useSnackbar();
    // STATE
    const { scUser } = useSCFetchUser({ id: userId, user });
    const [status, setStatus] = useState(null);
    const [disabled, setDisabled] = useState(false);
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    /**
     * Handle actions
     */
    const handleConnectionStatus = () => {
        if (!scUserContext.user) {
            scContext.settings.handleAnonymousAction();
        }
        else if (UserUtils.isBlocked(scUserContext.user)) {
            enqueueSnackbar(_jsx(FormattedMessage, { id: "ui.common.userBlocked", defaultMessage: "ui.common.userBlocked" }), {
                variant: 'warning',
                autoHideDuration: 3000
            });
        }
        else {
            let _action;
            if (status === SCConnectionStatus.CONNECTED) {
                _action = scConnectionsManager.removeConnection;
            }
            else if (status === SCConnectionStatus.CONNECTION_REQUEST_SENT) {
                _action = scConnectionsManager.cancelRequestConnection;
            }
            else if (status === SCConnectionStatus.CONNECTION_REQUEST_RECEIVED) {
                _action = scConnectionsManager.acceptConnection;
            }
            else if (status === null) {
                _action = scConnectionsManager.requestConnection;
            }
            _action(scUser).catch((e) => {
                Logger.error(SCOPE_SC_UI, e);
                if (catchUnauthorizedActionByBlockedUser(e, scUserContext.managers.blockedUsers.isBlocked(scUser), enqueueSnackbar)) {
                    setDisabled(true);
                }
                else {
                    enqueueSnackbar(_jsx(FormattedMessage, { id: "ui.common.actionToUserDeleted", defaultMessage: "ui.common.actionToUserDeleted" }), {
                        variant: 'warning',
                        autoHideDuration: 3000
                    });
                }
            });
        }
    };
    /**
     * Get current translated status
     */
    const getStatus = () => {
        let _status;
        switch (status) {
            case SCConnectionStatus.CONNECTED:
                _status = _jsx(FormattedMessage, { defaultMessage: "ui.friendshipUserButton.removeConnection", id: "ui.friendshipUserButton.removeConnection" });
                break;
            case SCConnectionStatus.CONNECTION_REQUEST_SENT:
                _status = (_jsx(FormattedMessage, { defaultMessage: "ui.friendshipUserButton.cancelConnectionRequest", id: "ui.friendshipUserButton.cancelConnectionRequest" }));
                break;
            case SCConnectionStatus.CONNECTION_REQUEST_RECEIVED:
                _status = _jsx(FormattedMessage, { defaultMessage: "ui.friendshipUserButton.acceptConnection", id: "ui.friendshipUserButton.acceptConnection" });
                break;
            default:
                _status = _jsx(FormattedMessage, { defaultMessage: "ui.friendshipUserButton.requestConnection", id: "ui.friendshipUserButton.requestConnection" });
                break;
        }
        return _status;
    };
    useEffect(() => {
        /**
         * Call scConnectionsManager.isFollowed inside an effect
         * to avoid warning rendering child during update parent state
         */
        if (authUserId && authUserId !== scUser.id) {
            const _status = scConnectionsManager.status(scUser);
            setStatus(_status);
        }
    }, [authUserId, scConnectionsManager.status]);
    // same user
    if (scUserContext.user && scUserContext.user.id === scUser.id) {
        return null;
    }
    return (_jsx(Root, Object.assign({ size: "small", variant: "outlined", disabled: disabled, loading: scUserContext.user ? scConnectionsManager.isLoading(scUser) : null, onClick: handleConnectionStatus, className: classNames(classes.root, className) }, rest, { children: getStatus() })));
}
