import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useContext, useEffect, useMemo, useReducer, useState } from 'react';
import { styled } from '@mui/material/styles';
import List from '@mui/material/List';
import { Button, CardContent, ListItem, Typography } from '@mui/material';
import { UserService } from '@selfcommunity/api-services';
import { CacheStrategies, isInteger, Logger } from '@selfcommunity/utils';
import { SCCache, SCPreferences, SCPreferencesContext, useSCUser } from '@selfcommunity/react-core';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
import Category, { CategorySkeleton } from '../Category';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { FormattedMessage } from 'react-intl';
import Skeleton from './Skeleton';
import classNames from 'classnames';
import BaseDialog from '../../shared/BaseDialog';
import Widget from '../Widget';
import { useThemeProps } from '@mui/system';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
import { PREFIX } from './constants';
const classes = {
    root: `${PREFIX}-root`,
    title: `${PREFIX}-title`,
    noResults: `${PREFIX}-no-results`,
    showMore: `${PREFIX}-show-more`,
    dialogRoot: `${PREFIX}-dialog-root`,
    endMessage: `${PREFIX}-end-message`
};
const Root = styled(Widget, {
    name: PREFIX,
    slot: 'Root'
})(() => ({}));
const DialogRoot = styled(BaseDialog, {
    name: PREFIX,
    slot: 'DialogRoot'
})(() => ({}));
/**
 * > API documentation for the Community-JS User Profile Categories Followed Widget component. Learn about the available props and the CSS API.
 *
 *
 * This component renders the list of the categories that the given user follows.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/UserFollowedCategories)

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCUserCategoriesFollowedWidget-root|Styles applied to the root element.|
 |title|.SCUserCategoriesFollowedWidget-title|Styles applied to the title element.|
 |noResults|.SCUserCategoriesFollowedWidget-no-results|Styles applied to no results section.|
 |showMore|.SCUserCategoriesFollowedWidget-show-more|Styles applied to show more button element.|
 |dialogRoot|.SCUserCategoriesFollowedWidget-dialog-root|Styles applied to the root dialog element.|
 |endMessage|.SCUserCategoriesFollowedWidget-end-message|Styles applied to the end message element.|
 * @param inProps
 */
export default function UserFollowedCategoriesWidget(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { userId, autoHide, limit = 3, className, CategoryProps = {}, cacheStrategy = CacheStrategies.NETWORK_ONLY, onHeightChange, onStateChange, DialogProps = {} } = props, rest = __rest(props, ["userId", "autoHide", "limit", "className", "CategoryProps", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps"]);
    // CONTEXT
    const scUserContext = useSCUser();
    const isMe = useMemo(() => scUserContext.user && userId === scUserContext.user.id, [scUserContext.user, userId]);
    const scPreferencesContext = useContext(SCPreferencesContext);
    const contentAvailability = useMemo(() => SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value, [scPreferencesContext]);
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.CATEGORIES_FOLLOWED_TOOLS_STATE_CACHE_PREFIX_KEY, userId),
        cacheStrategy
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    /**
     * Initialize component
     * Fetch data only if the component is not initialized and it is not loading data
     */
    const _initComponent = useMemo(() => () => {
        if (!state.initialized && !state.isLoadingNext) {
            UserService.getUserFollowedCategories(userId, null)
                .then((categories) => {
                dispatch({
                    type: actionWidgetTypes.LOAD_NEXT_SUCCESS,
                    payload: {
                        count: categories.length,
                        results: categories,
                        initialized: true
                    }
                });
            })
                .catch((error) => {
                dispatch({ type: actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                Logger.error(SCOPE_SC_UI, error);
            });
        }
    }, [state.isLoadingNext, state.initialized, userId, dispatch]);
    // EFFECTS
    useEffect(() => {
        var _a;
        let _t;
        if ((contentAvailability || (!contentAvailability && ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id))) && isInteger(userId) && scUserContext.user !== undefined) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [scUserContext.user, contentAvailability, userId]);
    /**
     * Virtual feed update
     */
    useEffect(() => {
        onHeightChange && onHeightChange();
    }, [state.results.length]);
    useEffect(() => {
        if ((!contentAvailability && !scUserContext.user) || !isInteger(userId)) {
            return;
        }
        else if (cacheStrategy === CacheStrategies.NETWORK_ONLY) {
            onStateChange && onStateChange({ cacheStrategy: CacheStrategies.CACHE_FIRST });
        }
    }, [contentAvailability, cacheStrategy, scUserContext.user, userId]);
    // HANDLERS
    const handleOnFollowCategory = (category) => {
        if (isMe) {
            const newCategories = [...state.results];
            const index = newCategories.findIndex((u) => u.id === category.id);
            if (index !== -1) {
                if (category.followed) {
                    newCategories[index].followers_counter = category.followers_counter - 1;
                    newCategories[index].followed = !category.followed;
                }
                else {
                    newCategories[index].followers_counter = category.followers_counter + 1;
                    newCategories[index].followed = !category.followed;
                }
                dispatch({ type: actionWidgetTypes.SET_RESULTS, payload: { results: newCategories } });
            }
        }
    };
    const handleToggleDialogOpen = () => {
        setOpenDialog((prev) => !prev);
    };
    // RENDER
    if ((autoHide && !state.count && state.initialized) || !userId) {
        return _jsx(HiddenPlaceholder, {});
    }
    if (!state.initialized) {
        return _jsx(Skeleton, {});
    }
    const content = (_jsxs(CardContent, { children: [_jsx(Typography, Object.assign({ className: classes.title, variant: "h5" }, { children: _jsx(FormattedMessage, { id: "ui.userFollowedCategoriesWidget.title", defaultMessage: "ui.userFollowedCategoriesWidget.title", values: { total: isMe ? state.results.filter((c) => c.followed).length : state.count } }) })), !state.count ? (_jsx(Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.userFollowedCategoriesWidget.subtitle.noResults", defaultMessage: "ui.userFollowedCategoriesWidget.subtitle.noResults" }) }))) : (_jsxs(React.Fragment, { children: [_jsx(List, { children: state.results.slice(0, limit).map((category) => (_jsx(ListItem, { children: _jsx(Category, Object.assign({ elevation: 0, category: category, categoryFollowButtonProps: { onFollow: handleOnFollowCategory } }, CategoryProps)) }, category.id))) }), limit < state.count && (_jsx(Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: _jsx(FormattedMessage, { id: "ui.userFollowedCategoriesWidget.button.showAll", defaultMessage: "ui.userFollowedCategoriesWidget.button.showAll" }) }))), openDialog && (_jsxs(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { id: "ui.userFollowedCategoriesWidget.title", defaultMessage: "ui.userFollowedCategoriesWidget.title", values: { total: state.count } }), onClose: handleToggleDialogOpen, open: openDialog, scroll: "paper" }, DialogProps, { children: [_jsxs(List, { children: [state.results.map((c) => (_jsx(ListItem, { children: _jsx(Category, Object.assign({ elevation: 0, category: c, categoryFollowButtonProps: { onFollow: handleOnFollowCategory } }, CategoryProps)) }, c.id))), state.isLoadingNext && (_jsx(ListItem, { children: _jsx(CategorySkeleton, Object.assign({ elevation: 0 }, CategoryProps)) }))] }), _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.userFollowedCategoriesWidget.noMoreResults", defaultMessage: "ui.userFollowedCategoriesWidget.noMoreResults" }) }))] })))] }))] }));
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}
