import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useEffect, useMemo, useReducer, useState } from 'react';
import { styled } from '@mui/material/styles';
import List from '@mui/material/List';
import { Button, CardContent, ListItem, Typography, useMediaQuery, useTheme } from '@mui/material';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { SCCache, SCPreferences, useSCFetchFeedObject, useSCPreferences, useSCUser } from '@selfcommunity/react-core';
import FeedObject, { FeedObjectSkeleton } from '../FeedObject';
import { FormattedMessage } from 'react-intl';
import { SCFeedObjectTemplateType } from '../../types/feedObject';
import CustomAdv from '../CustomAdv';
import classNames from 'classnames';
import BaseDialog from '../../shared/BaseDialog';
import InfiniteScroll from '../../shared/InfiniteScroll';
import Widget from '../Widget';
import { useThemeProps } from '@mui/system';
import { http, Endpoints, FeedObjectService } from '@selfcommunity/api-services';
import { CacheStrategies, Logger } from '@selfcommunity/utils';
import { SCCustomAdvPosition } from '@selfcommunity/types';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
import Skeleton from './Skeleton';
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'
})(() => ({}));
const PREFERENCES = [
    SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED,
    SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED,
    SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY
];
/**
 * > API documentation for the Community-JS Related FeedObjects component. Learn about the available props and the CSS API.
 *
 *
 * This component renders a list of related feed objects (posts, discussions or statuses).
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/RelatedFeedObjects)

 #### Import

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

 #### Component Name

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

 #### CSS

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

 *
 * @param inProps
 */
export default function RelatedFeedObjectWidget(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { feedObject, feedObjectId, feedObjectType, template = SCFeedObjectTemplateType.SNIPPET, className = null, autoHide = null, limit = 5, FeedObjectProps = {
        template: SCFeedObjectTemplateType.SNIPPET
    }, cacheStrategy = CacheStrategies.CACHE_FIRST, onHeightChange, onStateChange, DialogProps = {} } = props, rest = __rest(props, ["feedObject", "feedObjectId", "feedObjectType", "template", "className", "autoHide", "limit", "FeedObjectProps", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps"]);
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.RELATED_FEED_TOOLS_STATE_CACHE_PREFIX_KEY, feedObjectId),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    // CONTEXT
    const scUserContext = useSCUser();
    const scPreferences = useSCPreferences();
    // HOOKS
    const { obj } = useSCFetchFeedObject({ id: feedObjectId, feedObject, feedObjectType });
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const objId = obj ? obj.id : null;
    // MEMO
    const preferences = useMemo(() => {
        const _preferences = {};
        PREFERENCES.map((p) => (_preferences[p] = p in scPreferences.preferences ? scPreferences.preferences[p].value : null));
        return _preferences;
    }, [scPreferences.preferences]);
    /**
     * 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 });
            FeedObjectService.relatedFeedObjects(obj.type, obj.id, { 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);
            });
        }
    }, [objId, state.initialized, state.isLoadingNext, limit, dispatch]);
    // EFFECTS
    useEffect(() => {
        var _a;
        let _t;
        if (scUserContext.user !== undefined &&
            objId &&
            preferences &&
            (preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY] ||
                (!preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY] && ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id)))) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [objId, scUserContext.user, preferences]);
    // Add 10 - limit items to initial dialog page
    useEffect(() => {
        if (openDialog && state.next && state.results.length === limit && state.initialized) {
            dispatch({ type: actionWidgetTypes.LOADING_NEXT });
            FeedObjectService.relatedFeedObjects(obj.type, obj.id, { 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, obj]);
    /**
     * Virtual feed update
     */
    useEffect(() => {
        onHeightChange && onHeightChange();
    }, [state.results]);
    useEffect(() => {
        if (!preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY] && !scUserContext.user) {
            return;
        }
        else if ((obj === null || obj === void 0 ? void 0 : obj.id) !== null && cacheStrategy === CacheStrategies.NETWORK_ONLY) {
            onStateChange && onStateChange({ cacheStrategy: CacheStrategies.CACHE_FIRST });
        }
    }, [obj === null || obj === void 0 ? void 0 : obj.id, preferences, cacheStrategy, scUserContext.user]);
    // HANDLERS
    const handleNext = useMemo(() => () => {
        dispatch({ type: actionWidgetTypes.LOADING_NEXT });
        http
            .request({
            url: state.next,
            method: Endpoints.RelatedFeedObjects.method
        })
            .then((res) => {
            dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next]);
    const handleToggleDialogOpen = () => {
        setOpenDialog((prev) => !prev);
    };
    // RENDER
    if ((!preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY] && !scUserContext.user) || (autoHide && !state.count && state.initialized)) {
        return _jsx(HiddenPlaceholder, {});
    }
    if (!state.initialized) {
        return _jsx(Skeleton, {});
    }
    const renderAdvertising = () => {
        if (preferences[SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED] &&
            ((preferences[SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED] && scUserContext.user === null) ||
                !preferences[SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED])) {
            return (_jsx(ListItem, { children: _jsx(CustomAdv, Object.assign({ position: SCCustomAdvPosition.POSITION_RELATED_POSTS_COLUMN }, (obj.categories.length && { categoriesId: obj.categories.map((c) => c.id) }))) }));
        }
        return null;
    };
    const advPosition = Math.floor(Math.random() * (Math.min(state.count, 5) - 1 + 1) + 1);
    const content = (_jsxs(CardContent, { children: [_jsx(Typography, Object.assign({ className: classes.title, variant: "h5" }, { children: _jsx(FormattedMessage, { id: "ui.relatedFeedObjectsWidget.title", defaultMessage: "ui.relatedFeedObjectsWidget.title" }) })), !state.count ? (_jsx(Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.relatedFeedObjectsWidget.noResults", defaultMessage: "ui.relatedFeedObjectsWidget.noResults" }) }))) : (_jsxs(React.Fragment, { children: [_jsx(List, { children: state.results.slice(0, state.visibleItems).map((obj, index) => (_jsxs(React.Fragment, { children: [_jsx(ListItem, { children: _jsx(FeedObject, Object.assign({ elevation: 0, feedObject: obj, template: template }, FeedObjectProps)) }, obj.id), advPosition === index && renderAdvertising()] }, index))) }), state.count > state.visibleItems && (_jsx(Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: _jsx(FormattedMessage, { id: "ui.categoryTrendingFeedWidget.button.showAll", defaultMessage: "ui.categoryTrendingFeedWidget.button.showAll" }) })))] })), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { defaultMessage: "ui.categoryTrendingFeedWidget.title", id: "ui.categoryTrendingFeedWidget.title", values: { total: state.count } }), onClose: handleToggleDialogOpen, open: openDialog }, DialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: _jsx(FeedObjectSkeleton, Object.assign({ elevation: 0 }, FeedObjectProps)), height: isMobile ? '100%' : 400, endMessage: _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.categoryTrendingFeedWidget.noMoreResults", defaultMessage: "ui.categoryTrendingFeedWidget.noMoreResults" }) })) }, { children: _jsx(List, { children: state.results.map((obj) => (_jsx(ListItem, { children: _jsx(FeedObject, Object.assign({ elevation: 0, feedObject: obj }, FeedObjectProps)) }, obj.id))) }) })) })))] }));
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}
