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 { SCOPE_SC_UI } from '../../constants/Errors';
import { LoadingButton } from '@mui/lab';
import { FormattedMessage } from 'react-intl';
import { useSnackbar } from 'notistack';
import classNames from 'classnames';
import { Logger } from '@selfcommunity/utils';
import { useThemeProps } from '@mui/system';
import { catchUnauthorizedActionByBlockedUser } from '../../utils/errors';
import { SCUserContext, UserUtils, useSCContext, useSCFetchUser } from '@selfcommunity/react-core';
const PREFIX = 'SCFollowUserButton';
const classes = {
    root: `${PREFIX}-root`
};
const FollowButton = styled(LoadingButton, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(() => ({}));
/**
 * > API documentation for the Community-JS Follow User Button component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

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

 * @param inProps
 */
export default function FollowUserButton(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, userId, user, onFollow } = props, rest = __rest(props, ["className", "userId", "user", "onFollow"]);
    // CONTEXT
    const scContext = useSCContext();
    const scUserContext = useContext(SCUserContext);
    const scFollowedManager = scUserContext.managers.followed;
    const { enqueueSnackbar } = useSnackbar();
    // STATE
    const { scUser } = useSCFetchUser({ id: userId, user });
    const [followed, setFollowed] = useState(null);
    const [disabled, setDisabled] = useState(false);
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    useEffect(() => {
        /**
         * Call scFollowedManager.isFollowed inside an effect
         * to avoid warning rendering child during update parent state
         */
        if (scUserContext.user && scUserContext.user.id !== scUser.id) {
            setFollowed(scFollowedManager.isFollowed(scUser));
        }
    }, [authUserId, scFollowedManager.isFollowed]);
    const followUser = () => {
        if (!followed && UserUtils.isBlocked(scUserContext.user)) {
            enqueueSnackbar(_jsx(FormattedMessage, { id: "ui.common.userBlocked", defaultMessage: "ui.common.userBlocked" }), {
                variant: 'warning',
                autoHideDuration: 3000
            });
        }
        else {
            scFollowedManager
                .follow(scUser)
                .then(() => {
                onFollow && onFollow(scUser, !followed);
            })
                .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
                    });
                }
            });
        }
    };
    const handleFollowAction = () => {
        if (!scUserContext.user) {
            scContext.settings.handleAnonymousAction();
        }
        else {
            followUser();
        }
    };
    //same user
    if (scUserContext.user && scUserContext.user.id === scUser.id) {
        return null;
    }
    return (_jsx(FollowButton, Object.assign({ size: "small", variant: "outlined", onClick: handleFollowAction, loading: scUserContext.user ? followed === null || scFollowedManager.isLoading(scUser) : null, disabled: disabled, className: classNames(classes.root, className) }, rest, { children: scUserContext.user && followed ? (_jsx(FormattedMessage, { defaultMessage: "ui.followUserButton.unfollow", id: "ui.followUserButton.unfollow" })) : (_jsx(FormattedMessage, { defaultMessage: "ui.followUserButton.follow", id: "ui.followUserButton.follow" })) })));
}
