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, GroupService } from '@selfcommunity/api-services';
import { CacheStrategies, isInteger, Logger } from '@selfcommunity/utils';
import { SCCache, SCPreferences, useSCFetchGroup, useSCPreferences, useSCUser } from '@selfcommunity/react-core';
import { actionWidgetTypes, dataWidgetReducer, stateWidgetInitializer } from '../../utils/widget';
import Skeleton from './Skeleton';
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';
import User, { UserSkeleton } from '../User';
import GroupSubscribeButton from '../GroupSubscribeButton';
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 Group Requests Widget component. Learn about the available props and the CSS API.
 *
 *
 * This component displays the list of users who have requested access to the specified group.

 #### Import

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

 #### Component Name

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


 #### CSS

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

 * @param inProps
 */
export default function GroupRequestsWidget(inProps) {
    var _a;
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { groupId, group, limit = 5, className, cacheStrategy = CacheStrategies.NETWORK_ONLY, onHeightChange, onStateChange, UserProps = {}, DialogProps = {}, GroupSubscribeButtonProps = {}, onSubscribeActon } = props, rest = __rest(props, ["groupId", "group", "limit", "className", "cacheStrategy", "onHeightChange", "onStateChange", "UserProps", "DialogProps", "GroupSubscribeButtonProps", "onSubscribeActon"]);
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.GROUP_REQUESTS_TOOLS_STATE_CACHE_PREFIX_KEY, isInteger(groupId) ? groupId : group.id),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    // CONTEXT
    const scUserContext = useSCUser();
    const scPreferencesContext = useSCPreferences();
    const { scGroup } = useSCFetchGroup({ id: groupId, group });
    // MEMO
    const contentAvailability = useMemo(() => SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value, [scPreferencesContext.preferences]);
    // HOOKS
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const isGroupAdmin = useMemo(() => { var _a; return scUserContext.user && ((_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id) === scUserContext.user.id; }, [scUserContext.user, (_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id]);
    /**
     * 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 });
            GroupService.getGroupWaitingApprovalSubscribers(scGroup.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);
            });
        }
    }, [state.isLoadingNext, state.initialized, scGroup, limit, dispatch]);
    // EFFECTS
    useEffect(() => {
        var _a;
        let _t;
        if ((contentAvailability || (!contentAvailability && ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id))) && scGroup && scUserContext.user !== undefined) {
            _t = setTimeout(_initComponent);
            return () => {
                _t && clearTimeout(_t);
            };
        }
    }, [scUserContext.user, contentAvailability, scGroup]);
    useEffect(() => {
        if (openDialog && state.next && state.results.length === limit && state.initialized) {
            dispatch({ type: actionWidgetTypes.LOADING_NEXT });
            GroupService.getGroupWaitingApprovalSubscribers(scGroup.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, state.next, state.results.length, state.initialized, limit]);
    /**
     * Virtual feed update
     */
    useEffect(() => {
        onHeightChange && onHeightChange();
    }, [state.results]);
    useEffect(() => {
        if (!scGroup || (!contentAvailability && !scUserContext.user)) {
            return;
        }
        else if (cacheStrategy === CacheStrategies.NETWORK_ONLY) {
            onStateChange && onStateChange({ cacheStrategy: CacheStrategies.CACHE_FIRST });
        }
    }, [scUserContext.user, scGroup, contentAvailability]);
    useEffect(() => {
        if (!scGroup || !scUserContext.user || !state.initialized) {
            return;
        }
    }, []);
    // HANDLERS
    const handleNext = useMemo(() => () => {
        dispatch({ type: actionWidgetTypes.LOADING_NEXT });
        http
            .request({
            url: state.next,
            method: Endpoints.GetGroupWaitingApprovalSubscribers.method
        })
            .then((res) => {
            dispatch({ type: actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
        });
    }, [dispatch, state.next, state.isLoadingNext, state.initialized]);
    const handleToggleDialogOpen = () => {
        setOpenDialog((prev) => !prev);
    };
    const handleSubscribeAction = useMemo(() => (user) => {
        const newRequests = [...state.results];
        const _updated = newRequests.filter((u) => u.id !== user.id);
        dispatch({
            type: actionWidgetTypes.SET_RESULTS,
            payload: { results: newRequests.length > 1 ? _updated : [] }
        });
        onSubscribeActon && onSubscribeActon(user);
    }, [dispatch, state.count, state.results, onSubscribeActon]);
    // RENDER
    if ((!state.count && state.initialized) || !contentAvailability || !scGroup || !state.count || !state.results.length || !isGroupAdmin) {
        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.groupRequestsWidget.title", defaultMessage: "ui.groupRequestsWidget.title" }) })), _jsxs(React.Fragment, { children: [_jsx(List, { children: state.results.slice(0, state.visibleItems).map((user) => (_jsx(ListItem, { children: _jsx(User, { elevation: 0, actions: _jsx(GroupSubscribeButton, Object.assign({ group: scGroup, groupId: scGroup === null || scGroup === void 0 ? void 0 : scGroup.id, user: user, onSubscribe: () => handleSubscribeAction(user) }, GroupSubscribeButtonProps)), user: user, userId: user.id }) }, user.id))) }), state.count > state.visibleItems && (_jsx(Button, Object.assign({ className: classes.showMore, onClick: handleToggleDialogOpen }, { children: _jsx(FormattedMessage, { id: "ui.groupRequestsWidget.button.showMore", defaultMessage: "ui.groupRequestsWidget.button.showMore" }) })))] }), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { defaultMessage: "ui.groupRequestsWidget.dialogTitle", id: "ui.groupRequestsWidget.dialogTitle", values: { total: scGroup.subscribers_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.groupRequestsWidget.noMoreResults", defaultMessage: "ui.groupRequestsWidget.noMoreResults" }) })) }, { children: _jsx(List, { children: state.results.map((user) => (_jsx(ListItem, { children: _jsx(User, { elevation: 0, actions: _jsx(GroupSubscribeButton, Object.assign({ group: scGroup, groupId: scGroup === null || scGroup === void 0 ? void 0 : scGroup.id, user: user, onSubscribe: () => handleSubscribeAction(user) }, GroupSubscribeButtonProps)), user: user, userId: user.id }) }, user.id))) }) })) })))] }));
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}
