import { __rest } from "tslib";
import { jsx as _jsx } from "react/jsx-runtime";
import React, { useMemo, useState } from 'react';
import { FormattedMessage } from 'react-intl';
import LoadingButton from '@mui/lab/LoadingButton';
import { styled } from '@mui/material/styles';
import { Box, Tooltip } from '@mui/material';
import { SCOPE_SC_UI } from '../../../../constants/Errors';
import classNames from 'classnames';
import { useSnackbar } from 'notistack';
import Icon from '@mui/material/Icon';
import { SCContributionType } from '@selfcommunity/types';
import { Endpoints, http } from '@selfcommunity/api-services';
import { Logger } from '@selfcommunity/utils';
import { useSCContext, useSCFetchFeedObject, useSCUser } from '@selfcommunity/react-core';
import { catchUnauthorizedActionByBlockedUser } from '../../../../utils/errors';
import { PREFIX } from '../../constants';
const classes = {
    root: `${PREFIX}-action-follow-root`,
    button: `${PREFIX}-action-follow-button`,
    iconized: `${PREFIX}-action-follow-iconized`,
    followed: `${PREFIX}-action-follow-followed`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'ActionFollowRoot'
})(() => ({}));
export default function Follow(props) {
    // PROPS
    const { className = null, feedObjectId = null, feedObject = null, feedObjectType = SCContributionType.POST, handleFollow, iconized = true } = props, rest = __rest(props, ["className", "feedObjectId", "feedObject", "feedObjectType", "handleFollow", "iconized"]);
    // STATE
    const { obj, setObj } = useSCFetchFeedObject({ id: feedObjectId, feedObject, feedObjectType });
    const [isFollowing, setIsFollowing] = useState(false);
    // CONTEXT
    const scContext = useSCContext();
    const scUserContext = useSCUser();
    const { enqueueSnackbar } = useSnackbar();
    /**
     * Perform follow/unfollow
     * Post, Discussion, Status
     */
    const performFollow = useMemo(() => () => {
        return http
            .request({
            url: Endpoints.FollowContribution.url({ type: obj.type, id: obj.id }),
            method: Endpoints.FollowContribution.method
        })
            .then((res) => {
            if (res.status >= 300) {
                return Promise.reject(res);
            }
            return Promise.resolve(res.data);
        });
    }, [obj]);
    /**
     * Handle follow object
     * Even if a user is blocked, can perform this action
     */
    function follow() {
        if (!scUserContext.user) {
            scContext.settings.handleAnonymousAction();
        }
        else {
            setIsFollowing(true);
            performFollow()
                .then((data) => {
                const isFollow = !obj.followed;
                setObj(Object.assign({}, obj, { followed: isFollow }));
                setIsFollowing(false);
                handleFollow && handleFollow(isFollow);
            })
                .catch((error) => {
                Logger.error(SCOPE_SC_UI, error);
                if (!catchUnauthorizedActionByBlockedUser(error, scUserContext.managers.blockedUsers.isBlocked(obj.author), enqueueSnackbar)) {
                    enqueueSnackbar(_jsx(FormattedMessage, { id: "ui.common.error.action", defaultMessage: "ui.common.error.action" }), {
                        variant: 'error',
                        autoHideDuration: 3000
                    });
                }
                setIsFollowing(false);
            });
        }
    }
    /**
     * Renders vote action if withAction==true
     * @return {JSX.Element}
     */
    function renderFollowButton() {
        let btnLabel = _jsx(FormattedMessage, { id: "ui.feedObject.follow", defaultMessage: "ui.feedObject.follow" });
        if (obj.followed) {
            btnLabel = _jsx(FormattedMessage, { id: "ui.feedObject.unfollow", defaultMessage: "ui.feedObject.unfollow" });
        }
        return (_jsx(React.Fragment, { children: scUserContext.user && obj.author.id !== scUserContext.user.id && !obj.deleted && (_jsx(Tooltip, Object.assign({ title: btnLabel }, { children: _jsx(LoadingButton, Object.assign({ className: classNames(classes.button, { [classes.iconized]: iconized, [classes.followed]: obj.followed }), loading: isFollowing, variant: iconized ? 'text' : 'contained', disabled: isFollowing, onClick: follow }, { children: iconized ? _jsx(Icon, { children: obj.followed ? 'bookmark_added' : 'bookmark_border' }) : btnLabel })) }))) }));
    }
    /**
     * Renders share action
     */
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: renderFollowButton() })));
}
