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 { Button, List, Typography, Box, IconButton, ListItem, useTheme, useMediaQuery } from '@mui/material';
import CardContent from '@mui/material/CardContent';
import { http, Endpoints, IncubatorService } 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 classNames from 'classnames';
import BaseDialog from '../../shared/BaseDialog';
import InfiniteScroll from '../../shared/InfiniteScroll';
import Incubator, { IncubatorSkeleton } from '../Incubator';
import Popover from '@mui/material/Popover';
import Icon from '@mui/material/Icon';
import { useThemeProps } from '@mui/system';
import Widget from '../Widget';
import CreateIncubatorDialog from './CreateIncubatorDialog';
import IncubatorDetail from '../IncubatorDetail';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
import { SCCache, SCPreferences, SCPreferencesContext, SCUserContext } from '@selfcommunity/react-core';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
import { PREFIX } from './constants';
const classes = {
    root: `${PREFIX}-root`,
    header: `${PREFIX}-header`,
    title: `${PREFIX}-title`,
    noResults: `${PREFIX}-no-results`,
    showMore: `${PREFIX}-show-more`,
    actions: `${PREFIX}-actions`,
    helpPopover: `${PREFIX}-help-popover`,
    dialogRoot: `${PREFIX}-dialog-root`,
    endMessage: `${PREFIX}-end-message`,
    createDialog: `${PREFIX}-create-dialog`
};
const Root = styled(Widget, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({}));
const DialogRoot = styled(BaseDialog, {
    name: 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
 */
export default function IncubatorListWidget(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { autoHide = true, limit = 3, className, IncubatorProps = {}, cacheStrategy = CacheStrategies.CACHE_FIRST, onHeightChange, onStateChange, DialogProps = {} } = props, rest = __rest(props, ["autoHide", "limit", "className", "IncubatorProps", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps"]);
    // CONTEXT
    const scUserContext = useContext(SCUserContext);
    const scPreferencesContext = useContext(SCPreferencesContext);
    const contentAvailability = SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value;
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.INCUBATOR_LIST_TOOLS_STATE_CACHE_PREFIX_KEY),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    const [openCreateIncubatorDialog, setOpenCreateIncubatorDialog] = useState(false);
    const [openIncubatorDetailDialog, setOpenIncubatorDetailDialog] = useState(false);
    const [anchorEl, setAnchorEl] = React.useState(null);
    const isOpen = Boolean(anchorEl);
    const [detailObj, setDetailObj] = useState(null);
    // HOOKS
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    /**
     * 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 });
            IncubatorService.getAllIncubators({ 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]);
    //EFFECTS
    useEffect(() => {
        let _t;
        if (scUserContext.user !== undefined) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [scUserContext.user]);
    useEffect(() => {
        if (openDialog && state.next && state.initialized && state.results.length === limit) {
            dispatch({ type: actionWidgetTypes.LOADING_NEXT });
            IncubatorService.getAllIncubators({ 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, state.next, state.initialized, state.results.length, limit]);
    /**
     * 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, scUserContext.user]);
    // HANDLERS
    const handleClickHelpButton = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handlePopoverClose = useMemo(() => () => {
        setAnchorEl(null);
    }, [setAnchorEl]);
    const handleCreateIncubatorDialogClose = useMemo(() => () => {
        setOpenCreateIncubatorDialog(false);
    }, [setOpenCreateIncubatorDialog]);
    const handleIncubatorDetailDialogOpening = useMemo(() => (incubator) => {
        setOpenIncubatorDetailDialog(true);
        setOpenDialog(false);
        setDetailObj(incubator);
    }, [setOpenIncubatorDetailDialog, setOpenDialog, setDetailObj]);
    const handleIncubatorDetailDialogClose = useMemo(() => () => {
        setOpenIncubatorDetailDialog(false);
    }, [setOpenIncubatorDetailDialog]);
    const handleToggleDialogOpen = 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: actionWidgetTypes.SET_RESULTS, payload: { results: newIncubators } });
        }
    };
    /**
     * Handle pagination
     */
    const handleNext = useMemo(() => () => {
        dispatch({ type: actionWidgetTypes.LOADING_NEXT });
        http
            .request({
            url: state.next,
            method: Endpoints.GetAllIncubators.method
        })
            .then((res) => {
            dispatch({ type: 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 _jsx(HiddenPlaceholder, {});
    }
    if (!state.initialized) {
        return _jsx(Skeleton, {});
    }
    const content = (_jsxs(CardContent, { children: [_jsxs(Box, Object.assign({ className: classes.header }, { children: [_jsx(Typography, Object.assign({ className: classes.title, variant: 'h5' }, { children: _jsx(FormattedMessage, { id: "ui.incubatorListWidget.title", defaultMessage: "ui.incubatorListWidget.title" }) })), _jsx(IconButton, Object.assign({ className: classes.helpPopover, color: "primary", "aria-label": "info", component: "span", onClick: handleClickHelpButton }, { children: _jsx(Icon, { children: "help_outline" }) })), isOpen && (_jsx(Popover, Object.assign({ open: isOpen, anchorEl: anchorEl, onClose: handlePopoverClose, anchorOrigin: {
                            vertical: 'bottom',
                            horizontal: 'right'
                        } }, { children: _jsx(Box, Object.assign({ sx: { p: '10px' } }, { children: _jsx(Typography, Object.assign({ component: 'span', sx: { whiteSpace: 'pre-line' } }, { children: _jsx(FormattedMessage, { id: "ui.incubatorListWidget.popover", defaultMessage: "ui.incubatorListWidget.popover" }) })) })) })))] })), !state.count ? (_jsx(Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.incubatorListWidget.noResults", defaultMessage: "ui.incubatorListWidget.noResults" }) }))) : (_jsxs(React.Fragment, { children: [_jsx(List, { children: state.results.slice(0, state.visibleItems).map((incubator) => (_jsx(ListItem, { children: _jsx(Incubator, Object.assign({ elevation: 0, incubator: incubator, subscribeButtonProps: { onSubscribe: handleSubscriptionsUpdate }, ButtonProps: { onClick: () => handleIncubatorDetailDialogOpening(incubator) } }, IncubatorProps)) }, incubator.id))) }), _jsxs(Box, Object.assign({ className: classes.actions }, { children: [state.count > state.visibleItems && (_jsx(Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: _jsx(FormattedMessage, { id: "ui.incubatorListWidget.ShowAll", defaultMessage: "ui.incubatorListWidget.ShowAll" }) }))), _jsx(Button, Object.assign({ size: "small", onClick: () => setOpenCreateIncubatorDialog(true) }, { children: _jsx(FormattedMessage, { id: "ui.incubatorListWidget.SuggestNewTopic", defaultMessage: "ui.incubatorListWidget.SuggestNewTopic" }) }))] }))] })), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { id: "ui.incubatorListWidget.title", defaultMessage: "ui.incubatorListWidget.title" }), onClose: handleToggleDialogOpen, open: openDialog }, DialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: _jsx(IncubatorSkeleton, Object.assign({ elevation: 0 }, IncubatorProps)), height: isMobile ? '100vh' : 400, endMessage: _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.incubatorListWidget.noMoreIncubators", defaultMessage: "ui.incubatorListWidget.noMoreIncubators" }) })) }, { children: _jsx(List, { children: state.results.map((incubator) => (_jsx(ListItem, { children: _jsx(Incubator, Object.assign({ elevation: 0, incubator: incubator, subscribeButtonProps: { onSubscribe: handleSubscriptionsUpdate }, ButtonProps: { onClick: () => handleIncubatorDetailDialogOpening(incubator) } }, IncubatorProps)) }, incubator.id))) }) })) }))), openCreateIncubatorDialog && (_jsx(CreateIncubatorDialog, { className: classes.createDialog, open: openCreateIncubatorDialog, onClose: handleCreateIncubatorDialogClose })), openIncubatorDetailDialog && (_jsx(IncubatorDetail, { open: openIncubatorDetailDialog, onClose: handleIncubatorDetailDialogClose, incubator: detailObj, onSubscriptionsUpdate: handleSubscriptionsUpdate }))] }));
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}
