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 { Button, List, Typography, ListItem, useMediaQuery, useTheme } from '@mui/material';
import CardContent from '@mui/material/CardContent';
import { http, Endpoints, SuggestionService } from '@selfcommunity/api-services';
import { CacheStrategies, Logger } from '@selfcommunity/utils';
import { SCCache, useSCUser } from '@selfcommunity/react-core';
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 { useThemeProps } from '@mui/system';
import Widget from '../Widget';
import IncubatorDetail from '../IncubatorDetail';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
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 Incubator Suggestion component. Learn about the available props and the CSS API.
 *
 *
 * This component renders a list of suggested incubators.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/IncubatorSuggestion)

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

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

 #### CSS

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

 * @param inProps
 */
export default function IncubatorSuggestionWidget(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { autoHide = true, limit = 3, className, IncubatorProps = {}, cacheStrategy = CacheStrategies.NETWORK_ONLY, onHeightChange, onStateChange, DialogProps = {} } = props, rest = __rest(props, ["autoHide", "limit", "className", "IncubatorProps", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps"]);
    // CONTEXT
    const scUserContext = useSCUser();
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.INCUBATOR_SUGGESTION_TOOLS_STATE_CACHE_PREFIX_KEY),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    const [openIncubatorDetailDialog, setOpenIncubatorDetailDialog] = useState(false);
    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 });
            SuggestionService.getIncubatorSuggestion({ 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) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [scUserContext.user]);
    useEffect(() => {
        if (openDialog && state.next && state.results.length === limit && state.initialized) {
            dispatch({ type: actionWidgetTypes.LOADING_NEXT });
            SuggestionService.getIncubatorSuggestion({ 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.results.length, state.initialized, limit]);
    /**
     * Virtual feed update
     */
    useEffect(() => {
        onHeightChange && onHeightChange();
    }, [state.results]);
    useEffect(() => {
        if (scUserContext.user && cacheStrategy === CacheStrategies.NETWORK_ONLY) {
            onStateChange && onStateChange({ cacheStrategy: CacheStrategies.CACHE_FIRST });
        }
    }, [scUserContext.user, cacheStrategy]);
    // HANDLERS
    const handleIncubatorDetailDialogOpening = useMemo(() => (incubator) => {
        setOpenIncubatorDetailDialog(true);
        setOpenDialog(false);
        setDetailObj(incubator);
    }, [setOpenIncubatorDetailDialog, setOpenDialog, setDetailObj]);
    const handleIncubatorDetailDialogClose = () => {
        setOpenIncubatorDetailDialog(false);
    };
    const handleToggleDialogOpen = useMemo(() => () => {
        setOpenDialog((prev) => !prev);
    }, []);
    /**
     * 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 } });
        }
    };
    const handleNext = useMemo(() => () => {
        dispatch({ type: actionWidgetTypes.LOADING_NEXT });
        http
            .request({
            url: state.next,
            method: Endpoints.GetIncubatorSuggestion.method
        })
            .then((res) => {
            dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next, state.isLoadingNext, state.initialized]);
    // RENDER
    if ((autoHide && !state.count && state.initialized) || !scUserContext.user) {
        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.incubatorSuggestionWidget.title", defaultMessage: "ui.incubatorSuggestionWidget.title" }) })), !state.count ? (_jsx(Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.incubatorSuggestionWidget.noResults", defaultMessage: "ui.incubatorSuggestionWidget.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))) }), state.count > state.visibleItems && (_jsx(Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: _jsx(FormattedMessage, { id: "ui.incubatorSuggestionWidget.ShowAll", defaultMessage: "ui.incubatorSuggestionWidget.ShowAll" }) })))] })), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { id: "ui.incubatorSuggestionWidget.title", defaultMessage: "ui.incubatorSuggestionWidget.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.incubatorSuggestionWidget.noMoreIncubators", defaultMessage: "ui.incubatorSuggestionWidget.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))) }) })) }))), openIncubatorDetailDialog && (_jsx(IncubatorDetail, { open: openIncubatorDetailDialog, onClose: handleIncubatorDetailDialogClose, incubator: detailObj, onSubscriptionsUpdate: handleSubscriptionsUpdate }))] }));
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}
