"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 material_1 = require("@mui/material");
const CardContent_1 = tslib_1.__importDefault(require("@mui/material/CardContent"));
const api_services_1 = require("@selfcommunity/api-services");
const utils_1 = require("@selfcommunity/utils");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const Errors_1 = require("../../constants/Errors");
const react_intl_1 = require("react-intl");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const BaseDialog_1 = tslib_1.__importDefault(require("../../shared/BaseDialog"));
const InfiniteScroll_1 = tslib_1.__importDefault(require("../../shared/InfiniteScroll"));
const Incubator_1 = tslib_1.__importStar(require("../Incubator"));
const Popover_1 = tslib_1.__importDefault(require("@mui/material/Popover"));
const Icon_1 = tslib_1.__importDefault(require("@mui/material/Icon"));
const system_1 = require("@mui/system");
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const CreateIncubatorDialog_1 = tslib_1.__importDefault(require("./CreateIncubatorDialog"));
const IncubatorDetail_1 = tslib_1.__importDefault(require("../IncubatorDetail"));
const widget_1 = require("../../utils/widget");
const react_core_1 = require("@selfcommunity/react-core");
const HiddenPlaceholder_1 = tslib_1.__importDefault(require("../../shared/HiddenPlaceholder"));
const constants_1 = require("./constants");
const classes = {
    root: `${constants_1.PREFIX}-root`,
    header: `${constants_1.PREFIX}-header`,
    title: `${constants_1.PREFIX}-title`,
    noResults: `${constants_1.PREFIX}-no-results`,
    showMore: `${constants_1.PREFIX}-show-more`,
    actions: `${constants_1.PREFIX}-actions`,
    helpPopover: `${constants_1.PREFIX}-help-popover`,
    dialogRoot: `${constants_1.PREFIX}-dialog-root`,
    endMessage: `${constants_1.PREFIX}-end-message`,
    createDialog: `${constants_1.PREFIX}-create-dialog`
};
const Root = (0, styles_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({}));
const DialogRoot = (0, styles_1.styled)(BaseDialog_1.default, {
    name: constants_1.PREFIX,
    slot: 'DialogRoot'
})(({ theme }) => ({}));
/**
 * > API documentation for the Community-JS Incubator List Widget component. Learn about the available props and the CSS API.
 *
 *
 * This component renders a list of incubators.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/IncubatorsList)

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

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

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCIncubatorListWidget-root|Styles applied to the root element.|
 |header|.SCIncubatorListWidget-header|Styles applied to the header element.|
 |title|.SCIncubatorListWidget-title|Styles applied to the title element.|
 |noResults|.SCIncubatorListWidget-no-results|Styles applied to the no results section.|
 |showMore|.SCIncubatorListWidget-show-more|Styles applied to the show more button element.|
 |actions|.SCIncubatorListWidget-actions|Styles applied to the actions section.|
 |helpPopover|.SCIncubatorListWidget-help-popover|Styles applied to the help popover element.|
 |dialogRoot|.SCIncubatorListWidget-dialog-root|Styles applied to the root dialog element.|
 |endMessage|.SCIncubatorListWidget-end-message|Styles applied to the end message element.|
 |createDialog|.SCIncubatorListWidget-create-dialog|Styles applied to the create dialog element.|

 * @param inProps
 */
function IncubatorListWidget(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { autoHide = true, limit = 3, className, IncubatorProps = {}, cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST, onHeightChange, onStateChange, DialogProps = {} } = props, rest = tslib_1.__rest(props, ["autoHide", "limit", "className", "IncubatorProps", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps"]);
    // CONTEXT
    const scUserContext = (0, react_1.useContext)(react_core_1.SCUserContext);
    const scPreferencesContext = (0, react_1.useContext)(react_core_1.SCPreferencesContext);
    const contentAvailability = react_core_1.SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[react_core_1.SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value;
    // 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.INCUBATOR_LIST_TOOLS_STATE_CACHE_PREFIX_KEY),
        cacheStrategy,
        visibleItems: limit
    }, widget_1.stateWidgetInitializer);
    const [openDialog, setOpenDialog] = (0, react_1.useState)(false);
    const [openCreateIncubatorDialog, setOpenCreateIncubatorDialog] = (0, react_1.useState)(false);
    const [openIncubatorDetailDialog, setOpenIncubatorDetailDialog] = (0, react_1.useState)(false);
    const [anchorEl, setAnchorEl] = react_1.default.useState(null);
    const isOpen = Boolean(anchorEl);
    const [detailObj, setDetailObj] = (0, react_1.useState)(null);
    // HOOKS
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    /**
     * 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) {
            dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.IncubatorService.getAllIncubators({ limit })
                .then((payload) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { 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, limit, dispatch]);
    //EFFECTS
    (0, react_1.useEffect)(() => {
        let _t;
        if (scUserContext.user !== undefined) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [scUserContext.user]);
    (0, react_1.useEffect)(() => {
        if (openDialog && state.next && state.initialized && state.results.length === limit) {
            dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.IncubatorService.getAllIncubators({ offset: limit, limit: 10 })
                .then((payload) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: payload });
            })
                .catch((error) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [openDialog, state.next, state.initialized, state.results.length, limit]);
    /**
     * Virtual feed update
     */
    (0, react_1.useEffect)(() => {
        onHeightChange && onHeightChange();
    }, [state.results]);
    (0, react_1.useEffect)(() => {
        if (!contentAvailability && !scUserContext.user) {
            return;
        }
        else if (cacheStrategy === utils_1.CacheStrategies.NETWORK_ONLY) {
            onStateChange && onStateChange({ cacheStrategy: utils_1.CacheStrategies.CACHE_FIRST });
        }
    }, [contentAvailability, scUserContext.user]);
    // HANDLERS
    const handleClickHelpButton = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handlePopoverClose = (0, react_1.useMemo)(() => () => {
        setAnchorEl(null);
    }, [setAnchorEl]);
    const handleCreateIncubatorDialogClose = (0, react_1.useMemo)(() => () => {
        setOpenCreateIncubatorDialog(false);
    }, [setOpenCreateIncubatorDialog]);
    const handleIncubatorDetailDialogOpening = (0, react_1.useMemo)(() => (incubator) => {
        setOpenIncubatorDetailDialog(true);
        setOpenDialog(false);
        setDetailObj(incubator);
    }, [setOpenIncubatorDetailDialog, setOpenDialog, setDetailObj]);
    const handleIncubatorDetailDialogClose = (0, react_1.useMemo)(() => () => {
        setOpenIncubatorDetailDialog(false);
    }, [setOpenIncubatorDetailDialog]);
    const handleToggleDialogOpen = (0, react_1.useMemo)(() => () => {
        setOpenDialog((prev) => !prev);
    }, [setOpenDialog]);
    /**
     * Handles subscriptions counter update on subscribe/unsubscribe action.
     * @param incubator
     */
    const handleSubscriptionsUpdate = (incubator) => {
        const newIncubators = [...state.results];
        const index = newIncubators.findIndex((i) => i.id === incubator.id);
        if (index !== -1) {
            if (incubator.subscribed) {
                newIncubators[index].subscribers_count = incubator.subscribers_count - 1;
                newIncubators[index].subscribed = !incubator.subscribed;
            }
            else {
                newIncubators[index].subscribers_count = incubator.subscribers_count + 1;
                newIncubators[index].subscribed = !incubator.subscribed;
            }
            dispatch({ type: widget_1.actionWidgetTypes.SET_RESULTS, payload: { results: newIncubators } });
        }
    };
    /**
     * Handle pagination
     */
    const handleNext = (0, react_1.useMemo)(() => () => {
        dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
        api_services_1.http
            .request({
            url: state.next,
            method: api_services_1.Endpoints.GetAllIncubators.method
        })
            .then((res) => {
            dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next, state.isLoadingNext, state.initialized]);
    // RENDER
    if ((!contentAvailability && !scUserContext.user) || (state.initialized && autoHide && !state.count)) {
        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)(CardContent_1.default, { children: [(0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.header }, { 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.incubatorListWidget.title", defaultMessage: "ui.incubatorListWidget.title" }) })), (0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ className: classes.helpPopover, color: "primary", "aria-label": "info", component: "span", onClick: handleClickHelpButton }, { children: (0, jsx_runtime_1.jsx)(Icon_1.default, { children: "help_outline" }) })), isOpen && ((0, jsx_runtime_1.jsx)(Popover_1.default, Object.assign({ open: isOpen, anchorEl: anchorEl, onClose: handlePopoverClose, anchorOrigin: {
                            vertical: 'bottom',
                            horizontal: 'right'
                        } }, { children: (0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ sx: { p: '10px' } }, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ component: 'span', sx: { whiteSpace: 'pre-line' } }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.incubatorListWidget.popover", defaultMessage: "ui.incubatorListWidget.popover" }) })) })) })))] })), !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.incubatorListWidget.noResults", defaultMessage: "ui.incubatorListWidget.noResults" }) }))) : ((0, jsx_runtime_1.jsxs)(react_1.default.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.List, { children: state.results.slice(0, state.visibleItems).map((incubator) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(Incubator_1.default, Object.assign({ elevation: 0, incubator: incubator, subscribeButtonProps: { onSubscribe: handleSubscriptionsUpdate }, ButtonProps: { onClick: () => handleIncubatorDetailDialogOpening(incubator) } }, IncubatorProps)) }, incubator.id))) }), (0, jsx_runtime_1.jsxs)(material_1.Box, Object.assign({ className: classes.actions }, { children: [state.count > state.visibleItems && ((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.incubatorListWidget.ShowAll", defaultMessage: "ui.incubatorListWidget.ShowAll" }) }))), (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ size: "small", onClick: () => setOpenCreateIncubatorDialog(true) }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.incubatorListWidget.SuggestNewTopic", defaultMessage: "ui.incubatorListWidget.SuggestNewTopic" }) }))] }))] })), openDialog && ((0, jsx_runtime_1.jsx)(DialogRoot, Object.assign({ className: classes.dialogRoot, title: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.incubatorListWidget.title", defaultMessage: "ui.incubatorListWidget.title" }), onClose: handleToggleDialogOpen, open: openDialog }, DialogProps, { children: (0, jsx_runtime_1.jsx)(InfiniteScroll_1.default, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: (0, jsx_runtime_1.jsx)(Incubator_1.IncubatorSkeleton, Object.assign({ elevation: 0 }, IncubatorProps)), height: isMobile ? '100vh' : 400, endMessage: (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.incubatorListWidget.noMoreIncubators", defaultMessage: "ui.incubatorListWidget.noMoreIncubators" }) })) }, { children: (0, jsx_runtime_1.jsx)(material_1.List, { children: state.results.map((incubator) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(Incubator_1.default, Object.assign({ elevation: 0, incubator: incubator, subscribeButtonProps: { onSubscribe: handleSubscriptionsUpdate }, ButtonProps: { onClick: () => handleIncubatorDetailDialogOpening(incubator) } }, IncubatorProps)) }, incubator.id))) }) })) }))), openCreateIncubatorDialog && ((0, jsx_runtime_1.jsx)(CreateIncubatorDialog_1.default, { className: classes.createDialog, open: openCreateIncubatorDialog, onClose: handleCreateIncubatorDialogClose })), openIncubatorDetailDialog && ((0, jsx_runtime_1.jsx)(IncubatorDetail_1.default, { open: openIncubatorDetailDialog, onClose: handleIncubatorDetailDialogClose, incubator: detailObj, onSubscriptionsUpdate: handleSubscriptionsUpdate }))] }));
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, rest, { children: content })));
}
exports.default = IncubatorListWidget;
