"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = tslib_1.__importStar(require("react"));
const styles_1 = require("@mui/material/styles");
const List_1 = tslib_1.__importDefault(require("@mui/material/List"));
const material_1 = require("@mui/material");
const api_services_1 = require("@selfcommunity/api-services");
const utils_1 = require("@selfcommunity/utils");
const react_core_1 = require("@selfcommunity/react-core");
const widget_1 = require("../../utils/widget");
const types_1 = require("@selfcommunity/types");
const Errors_1 = require("../../constants/Errors");
const react_intl_1 = require("react-intl");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const BaseDialog_1 = tslib_1.__importDefault(require("../../shared/BaseDialog"));
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const system_1 = require("@mui/system");
const HiddenPlaceholder_1 = tslib_1.__importDefault(require("../../shared/HiddenPlaceholder"));
const constants_1 = require("./constants");
const Group_1 = tslib_1.__importStar(require("../Group"));
const classes = {
    root: `${constants_1.PREFIX}-root`,
    title: `${constants_1.PREFIX}-title`,
    noResults: `${constants_1.PREFIX}-no-results`,
    showMore: `${constants_1.PREFIX}-show-more`,
    dialogRoot: `${constants_1.PREFIX}-dialog-root`,
    endMessage: `${constants_1.PREFIX}-end-message`
};
const Root = (0, styles_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'Root'
})(() => ({}));
const DialogRoot = (0, styles_1.styled)(BaseDialog_1.default, {
    name: constants_1.PREFIX,
    slot: 'DialogRoot'
})(() => ({}));
/**
 * > API documentation for the Community-JS User Profile Groups Subscribed Widget component. Learn about the available props and the CSS API.
 *
 *
 * This component renders the list of the groups that the given user follows.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/UserSubscribedGroups)

 #### Import
 ```jsx
 import {UserSubscribedGroupsWidget} from '@selfcommunity/react-ui';
 ```
 #### Component Name
 The name `SCUserSubscribedGroupsWidget` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCUserSubscribedGroupsWidget-root|Styles applied to the root element.|
 |title|.SCUserSubscribedGroupsWidget-title|Styles applied to the title element.|
 |noResults|.SCUserSubscribedGroupsWidget-no-results|Styles applied to no results section.|
 |showMore|.SCUserSubscribedGroupsWidget-show-more|Styles applied to show more button element.|
 |dialogRoot|.SCUserSubscribedGroupsWidget-dialog-root|Styles applied to the root dialog element.|
 |endMessage|.SCUserSubscribedGroupsWidget-end-message|Styles applied to the end message element.|
 * @param inProps
 */
function UserSubscribedGroupsWidget(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { userId, autoHide, limit = 3, className, GroupProps = {}, cacheStrategy = utils_1.CacheStrategies.NETWORK_ONLY, onHeightChange, onStateChange, DialogProps = {} } = props, rest = tslib_1.__rest(props, ["userId", "autoHide", "limit", "className", "GroupProps", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps"]);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    const isMe = (0, react_1.useMemo)(() => scUserContext.user && userId === scUserContext.user.id, [scUserContext.user, userId]);
    const { preferences, features } = (0, react_core_1.useSCPreferences)();
    const groupsEnabled = (0, react_1.useMemo)(() => preferences &&
        features &&
        features.includes(types_1.SCFeatureName.TAGGING) &&
        features.includes(types_1.SCFeatureName.GROUPING) &&
        react_core_1.SCPreferences.CONFIGURATIONS_GROUPS_ENABLED in preferences &&
        preferences[react_core_1.SCPreferences.CONFIGURATIONS_GROUPS_ENABLED].value, [preferences, features]);
    // STATE
    const [state, dispatch] = (0, react_1.useReducer)(widget_1.dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: react_core_1.SCCache.getWidgetStateCacheKey(react_core_1.SCCache.GROUPS_SUBSCRIBED_TOOLS_STATE_CACHE_PREFIX_KEY, userId),
        cacheStrategy
    }, widget_1.stateWidgetInitializer);
    const [openDialog, setOpenDialog] = (0, react_1.useState)(false);
    /**
     * Initialize component
     * Fetch data only if the component is not initialized and it is not loading data
     */
    const _initComponent = (0, react_1.useMemo)(() => () => {
        if (!state.initialized && !state.isLoadingNext) {
            api_services_1.GroupService.getUserSubscribedGroups(userId)
                .then((groups) => {
                dispatch({
                    type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS,
                    payload: {
                        count: groups.count,
                        results: groups.results,
                        initialized: true
                    }
                });
            })
                .catch((error) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [state.isLoadingNext, state.initialized, userId, dispatch]);
    // EFFECTS
    (0, react_1.useEffect)(() => {
        let _t;
        if (groupsEnabled && (0, utils_1.isInteger)(userId) && scUserContext.user !== undefined) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [scUserContext.user, groupsEnabled, userId]);
    /**
     * Virtual feed update
     */
    (0, react_1.useEffect)(() => {
        onHeightChange && onHeightChange();
    }, [state.results.length]);
    (0, react_1.useEffect)(() => {
        if (!groupsEnabled && !scUserContext.user && !(0, utils_1.isInteger)(userId)) {
            return;
        }
        else if (cacheStrategy === utils_1.CacheStrategies.NETWORK_ONLY) {
            onStateChange && onStateChange({ cacheStrategy: utils_1.CacheStrategies.CACHE_FIRST });
        }
    }, [groupsEnabled, cacheStrategy, scUserContext.user, userId]);
    // HANDLERS
    const handleOnSubscribe = (group) => {
        if (isMe) {
            const newGroups = [...state.results];
            const index = newGroups.findIndex((u) => u.id === group.id);
            if (index !== -1) {
                if (group.subscription_status === types_1.SCGroupSubscriptionStatusType.SUBSCRIBED) {
                    newGroups[index].subscribers_counter = group.subscribers_counter - 1;
                    newGroups[index].subscription_status = null;
                }
                else {
                    newGroups[index].subscribers_counter =
                        group.privacy === types_1.SCGroupPrivacyType.PUBLIC ? group.subscribers_counter + 1 : group.subscribers_counter;
                    newGroups[index].subscription_status =
                        group.privacy === types_1.SCGroupPrivacyType.PUBLIC ? types_1.SCGroupSubscriptionStatusType.SUBSCRIBED : types_1.SCGroupSubscriptionStatusType.REQUESTED;
                }
                dispatch({ type: widget_1.actionWidgetTypes.SET_RESULTS, payload: { results: newGroups } });
            }
        }
    };
    const handleToggleDialogOpen = () => {
        setOpenDialog((prev) => !prev);
    };
    // RENDER
    if (!groupsEnabled || (autoHide && !state.count && state.initialized) || !userId) {
        return (0, jsx_runtime_1.jsx)(HiddenPlaceholder_1.default, {});
    }
    if (!state.initialized) {
        return (0, jsx_runtime_1.jsx)(Skeleton_1.default, {});
    }
    const content = ((0, jsx_runtime_1.jsxs)(material_1.CardContent, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.title, variant: "h5" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.userSubscribedGroupsWidget.title", defaultMessage: "ui.userSubscribedGroupsWidget.title", values: {
                        total: isMe ? state.results.filter((g) => g.subscription_status === types_1.SCGroupSubscriptionStatusType.SUBSCRIBED).length : state.count
                    } }) })), !state.count ? ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.userSubscribedGroupsWidget.subtitle.noResults", defaultMessage: "ui.userSubscribedGroupsWidget.subtitle.noResults" }) }))) : ((0, jsx_runtime_1.jsxs)(react_1.default.Fragment, { children: [(0, jsx_runtime_1.jsx)(List_1.default, { children: state.results.slice(0, limit).map((group) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(Group_1.default, Object.assign({ elevation: 0, group: group, groupSubscribeButtonProps: { onSubscribe: handleOnSubscribe } }, GroupProps)) }, group.id))) }), limit < state.count && ((0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.userSubscribedGroupsWidget.button.showAll", defaultMessage: "ui.userSubscribedGroupsWidget.button.showAll" }) }))), openDialog && ((0, jsx_runtime_1.jsxs)(DialogRoot, Object.assign({ className: classes.dialogRoot, title: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.userSubscribedGroupsWidget.title", defaultMessage: "ui.userSubscribedGroupsWidget.title", values: { total: state.count } }), onClose: handleToggleDialogOpen, open: openDialog, scroll: "paper" }, DialogProps, { children: [(0, jsx_runtime_1.jsxs)(List_1.default, { children: [state.results.map((g) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(Group_1.default, Object.assign({ elevation: 0, group: g, groupSubscribeButtonProps: { onSubscribe: handleOnSubscribe } }, GroupProps)) }, g.id))), state.isLoadingNext && ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(Group_1.GroupSkeleton, Object.assign({ elevation: 0 }, GroupProps)) }))] }), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.endMessage }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.userSubscribedGroupsWidget.noMoreResults", defaultMessage: "ui.userSubscribedGroupsWidget.noMoreResults" }) }))] })))] }))] }));
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, rest, { children: content })));
}
exports.default = UserSubscribedGroupsWidget;
