import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useContext, useEffect, useMemo, useReducer, useRef, useState } from 'react';
import { styled } from '@mui/material/styles';
import { Button, CardContent, List, ListItem, Typography, useMediaQuery, useTheme } from '@mui/material';
import { CategoryService, Endpoints, http } from '@selfcommunity/api-services';
import { CacheStrategies, Logger } from '@selfcommunity/utils';
import Skeleton from './Skeleton';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { FormattedMessage } from 'react-intl';
import Category, { CategorySkeleton } from '../Category';
import classNames from 'classnames';
import BaseDialog from '../../shared/BaseDialog';
import InfiniteScroll from '../../shared/InfiniteScroll';
import Widget from '../Widget';
import { useThemeProps } from '@mui/system';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
import { SCCache, SCPreferences, SCPreferencesContext, SCUserContext } from '@selfcommunity/react-core';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
import { PREFIX } from './constants';
import PubSub from 'pubsub-js';
import { SCCategoryEventType, SCTopicType } from '../../constants/PubSub';
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 Categories Popular widget component. Learn about the available props and the CSS API.
 *
 *
 * This component renders a list of popular categories.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/CategoriesPopular)

 #### Import
 ```jsx
 import {CategoriesPopular} from '@selfcommunity/react-ui';
 ```

 #### Component Name
 The name `SCCategoriesPopularWidget` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCCategoriesPopularWidget-root|Styles applied to the root element.|
 |title|.SCCategoriesPopularWidget-title|Styles applied to the title element.|
 |noResults|.SCCategoriesPopularWidget-no-results|Styles applied to no results section.|
 |showMore|.SCCategoriesPopularWidget-show-more|Styles applied to show more button element.|
 |dialogRoot|.SCCategoriesPopularWidget-dialog-root|Styles applied to the root dialog element.|
 |endMessage|.SCCategoriesPopularWidget-end-message|Styles applied to the end message element.|

 * @param inProps
 */
export default function CategoriesPopularWidget(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { autoHide = true, limit = 3, className, CategoryProps = {}, cacheStrategy = CacheStrategies.CACHE_FIRST, onHeightChange, onStateChange, DialogProps = {}, categoryId } = props, // Removed from root DOM
    rest = __rest(props, ["autoHide", "limit", "className", "CategoryProps", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps", "categoryId"]);
    // CONTEXT
    const scUserContext = useContext(SCUserContext);
    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_POPULAR_TOOLS_STATE_CACHE_PREFIX_KEY),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    // HOOKS
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    // REFS
    const updatesSubscription = useRef(null);
    /**
     * 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) {
            dispatch({ type: actionWidgetTypes.LOADING_NEXT });
            CategoryService.getPopularCategories({ limit })
                .then((payload) => {
                dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
            })
                .catch((error) => {
                dispatch({ type: actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                Logger.error(SCOPE_SC_UI, error);
            });
        }
    }, [state.isLoadingNext, state.initialized, limit, dispatch]);
    /**
     * Subscriber for pubsub callback
     */
    const onEditCategoryHandler = useCallback((_msg, edited) => {
        const _categories = [...state.results];
        const updatedCategories = _categories.map((c) => (c.id === edited.id ? Object.assign(Object.assign({}, c), edited) : c));
        dispatch({ type: actionWidgetTypes.SET_RESULTS, payload: { results: updatedCategories } });
    }, [dispatch, state.results]);
    /**
     * On mount, subscribe to receive event updates (only edit)
     */
    useEffect(() => {
        updatesSubscription.current = PubSub.subscribe(`${SCTopicType.CATEGORY}.${SCCategoryEventType.EDIT}`, onEditCategoryHandler);
        return () => {
            updatesSubscription.current && PubSub.unsubscribe(updatesSubscription.current);
        };
    }, [onEditCategoryHandler]);
    // EFFECTS
    useEffect(() => {
        var _a;
        let _t;
        if (scUserContext.user !== undefined && (contentAvailability || (!contentAvailability && ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id)))) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [scUserContext.user, contentAvailability]);
    useEffect(() => {
        if (openDialog && state.next && state.initialized && state.results.length === limit) {
            CategoryService.getPopularCategories({ offset: limit, limit: 10 })
                .then((payload) => {
                dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: payload });
            })
                .catch((error) => {
                dispatch({ type: actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                Logger.error(SCOPE_SC_UI, error);
            });
        }
    }, [openDialog, limit, state.next, state.initialized, state.results.length]);
    /**
     * Virtual feed update
     */
    useEffect(() => {
        onHeightChange && onHeightChange();
    }, [state.results]);
    useEffect(() => {
        if (!contentAvailability && !scUserContext.user) {
            return;
        }
        else if (cacheStrategy === CacheStrategies.NETWORK_ONLY) {
            onStateChange && onStateChange({ cacheStrategy: CacheStrategies.CACHE_FIRST });
        }
    }, [contentAvailability, cacheStrategy, scUserContext.user]);
    // HANDLERS
    /**
     * Fetches popular categories list
     */
    const handleNext = useMemo(() => () => {
        dispatch({ type: actionWidgetTypes.LOADING_NEXT });
        http
            .request({
            url: state.next,
            method: Endpoints.PopularCategories.method
        })
            .then((res) => {
            dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next, state.isLoadingNext, state.initialized]);
    /**
     * Update counters above the category name and the user follow state
     * @param category
     */
    const handleFollowersUpdate = (category) => {
        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 ((!contentAvailability && !scUserContext.user) || (state.initialized && autoHide && !state.count)) {
        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.categoriesPopularWidget.title", defaultMessage: "ui.categoriesPopularWidget.title" }) })), !state.count ? (_jsx(Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.categoriesPopularWidget.noResults", defaultMessage: "ui.categoriesPopularWidget.noResults" }) }))) : (_jsxs(React.Fragment, { children: [_jsx(List, { children: state.results.slice(0, state.visibleItems).map((category) => (_jsx(ListItem, { children: _jsx(Category, Object.assign({ elevation: 0, category: category, categoryFollowButtonProps: { onFollow: handleFollowersUpdate } }, CategoryProps)) }, category.id))) }), state.count > state.visibleItems && (_jsx(Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: _jsx(FormattedMessage, { id: "ui.categoriesPopularWidget.button.showAll", defaultMessage: "ui.categoriesPopularWidget.button.showAll" }) })))] })), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { defaultMessage: "ui.categoriesPopularWidget.title", id: "ui.categoriesPopularWidget.title" }), onClose: handleToggleDialogOpen, open: openDialog }, DialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: _jsx(CategorySkeleton, Object.assign({ elevation: 0 }, CategoryProps)), height: isMobile ? '100%' : 400, endMessage: _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.categoriesPopularWidget.noMoreResults", defaultMessage: "ui.categoriesPopularWidget.noMoreResults" }) })) }, { children: _jsx(List, { children: state.results.map((c) => (_jsx(ListItem, { children: _jsx(Category, Object.assign({ elevation: 0, category: c }, CategoryProps, { categoryFollowButtonProps: { onFollow: handleFollowersUpdate } })) }, c.id))) }) })) })))] }));
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}
