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 Widget from '../Widget';
import { http, Endpoints, UserService } from '@selfcommunity/api-services';
import { CacheStrategies, isInteger, Logger } from '@selfcommunity/utils';
import { SCCache, SCPreferences, useSCPreferences, useSCUser } from '@selfcommunity/react-core';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
import Skeleton from './Skeleton';
import User, { UserSkeleton } from '../User';
import { FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import { SCOPE_SC_UI } from '../../constants/Errors';
import BaseDialog from '../../shared/BaseDialog';
import InfiniteScroll from '../../shared/InfiniteScroll';
import { useThemeProps } from '@mui/system';
import HiddenPlaceholder from '../../shared/HiddenPlaceholder';
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 User Connections Requests Widget component. Learn about the available props and the CSS API.
 *
 *
 * This component renders the list of connections requests sent of the authenticated user.

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCUserConnectionsRequestsSentWidget-root|Styles applied to the root element.|
 |title|.SCUserConnectionsRequestsSentWidget-title|Styles applied to the title element.|
 |noResults|.SCUserConnectionsRequestsSentWidget-no-results|Styles applied to no results section.|
 |connectionsItem|.SCUserConnectionsRequestsSentWidget-connections-item|Styles applied to connection item element.|
 |showMore|.SCUserConnectionsRequestsSentWidget-show-more|Styles applied to show more button element.|

 * @param inProps
 */
export default function UserConnectionsRequestsSentWidget(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { autoHide = false, limit = 3, className, UserProps = {}, cacheStrategy = CacheStrategies.NETWORK_ONLY, onHeightChange, onStateChange, DialogProps = {}, userId } = props, rest = __rest(props, ["autoHide", "limit", "className", "UserProps", "cacheStrategy", "onHeightChange", "onStateChange", "DialogProps", "userId"]);
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.USER_CONNECTIONS_REQUESTS_SENT_TOOLS_STATE_CACHE_PREFIX_KEY, userId),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    // CONTEXT
    const scUserContext = useSCUser();
    const scPreferencesContext = useSCPreferences();
    // MEMO
    const contentAvailability = useMemo(() => SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value, [scPreferencesContext.preferences]);
    const followEnabled = useMemo(() => SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_FOLLOW_ENABLED].value, [scPreferencesContext.preferences]);
    // 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 });
            UserService.getUserRequestConnectionsSent({ 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, userId, limit, dispatch]);
    // EFFECTS
    useEffect(() => {
        let _t;
        if (!followEnabled && scUserContext.user) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [scUserContext.user, contentAvailability, userId]);
    useEffect(() => {
        if (openDialog && state.next && state.results.length === limit && state.initialized) {
            dispatch({ type: actionWidgetTypes.LOADING_NEXT });
            UserService.getUserRequestConnectionsSent({ 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 (!isInteger(userId) || followEnabled || (!contentAvailability && !scUserContext.user)) {
            return;
        }
        else if (cacheStrategy === CacheStrategies.NETWORK_ONLY) {
            onStateChange && onStateChange({ cacheStrategy: CacheStrategies.CACHE_FIRST });
        }
    }, [scUserContext.user, userId, contentAvailability]);
    // HANDLERS
    const handleNext = useMemo(() => () => {
        dispatch({ type: actionWidgetTypes.LOADING_NEXT });
        http
            .request({
            url: state.next,
            method: Endpoints.UserRequestConnectionsSent.method
        })
            .then((res) => {
            dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next, state.isLoadingNext, state.initialized]);
    /**
     * Handle refresh counters (authenticated user)
     */
    const handleChangeConnectionStatus = useMemo(() => () => {
        scUserContext.refreshCounters();
    }, [scUserContext.refreshCounters]);
    const handleToggleDialogOpen = () => {
        setOpenDialog((prev) => !prev);
    };
    // RENDER
    if (followEnabled || (autoHide && !state.count && state.initialized) || (!contentAvailability && !scUserContext.user) || !userId) {
        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.userConnectionsRequestsSentWidget.title", defaultMessage: "ui.userConnectionsRequestsSentWidget.title", values: { total: scUserContext.user.connection_requests_sent_counter } }) })), !state.count ? (_jsx(Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.userConnectionsRequestsSentWidget.subtitle.noResults", defaultMessage: "" }) }))) : (_jsxs(React.Fragment, { children: [_jsx(List, { children: state.results.slice(0, state.visibleItems).map((conReq) => (_jsx(ListItem, { children: _jsx(User, Object.assign({ elevation: 0, user: conReq.to_user, followConnectUserButtonProps: { followConnectUserButtonProps: { onChangeConnectionStatus: handleChangeConnectionStatus } } }, UserProps)) }, conReq.to_user.id))) }), state.count > state.visibleItems && (_jsx(Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: _jsx(FormattedMessage, { id: "ui.userConnectionsRequestsSentWidget.button.showAll", defaultMessage: "ui.userConnectionsRequestsSentWidget.button.showAll" }) })))] })), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { defaultMessage: "ui.userConnectionsRequestsSentWidget.title", id: "ui.userConnectionsRequestsSentWidget.title", values: { total: scUserContext.user.connection_requests_sent_counter } }), onClose: handleToggleDialogOpen, open: openDialog }, DialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: state.results.length, next: handleNext, hasMoreNext: Boolean(state.next), loaderNext: _jsx(UserSkeleton, Object.assign({ elevation: 0 }, UserProps)), height: isMobile ? '100%' : 400, endMessage: _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.userConnectionsRequestsSentWidget.noMoreResults", defaultMessage: "ui.userConnectionsRequestsSentWidget.noMoreResults" }) })) }, { children: _jsx(List, { children: state.results.map((conReq) => (_jsx(ListItem, { children: _jsx(User, Object.assign({ elevation: 0, user: conReq.to_user, followConnectUserButtonProps: { followConnectUserButtonProps: { onChangeConnectionStatus: handleChangeConnectionStatus } } }, UserProps)) }, conReq.to_user.id))) }) })) })))] }));
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}
