import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } 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, CardActions, 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 { Link, SCCache, SCPreferences, SCRoutes, useSCFetchGroup, useSCPreferences, useSCRouting, 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 GroupInviteButton from '../GroupInviteButton';
import GroupSettingsIconButton from '../GroupSettingsIconButton';
const classes = {
    root: `${PREFIX}-root`,
    title: `${PREFIX}-title`,
    actions: `${PREFIX}-actions`,
    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 Members Widget component. Learn about the available props and the CSS API.
 *
 *
 * This component renders the list of the follows of the given group.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/GroupMembers)

 #### Import

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

 #### Component Name

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


 #### CSS

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

 * @param inProps
 */
export default function GroupMembersWidget(inProps) {
    var _a;
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { groupId, group, autoHide = false, limit = 5, className, cacheStrategy = CacheStrategies.NETWORK_ONLY, onHeightChange, onStateChange, UserProps = {}, DialogProps = {} } = props, rest = __rest(props, ["groupId", "group", "autoHide", "limit", "className", "cacheStrategy", "onHeightChange", "onStateChange", "UserProps", "DialogProps"]);
    // STATE
    const [state, dispatch] = useReducer(dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: SCCache.getWidgetStateCacheKey(SCCache.GROUP_MEMBERS_TOOLS_STATE_CACHE_PREFIX_KEY, isInteger(groupId) ? groupId : group.id),
        cacheStrategy,
        visibleItems: limit
    }, stateWidgetInitializer);
    const [openDialog, setOpenDialog] = useState(false);
    // CONTEXT
    const scUserContext = useSCUser();
    const scRoutingContext = useSCRouting();
    const scPreferencesContext = useSCPreferences();
    const { scGroup } = useSCFetchGroup({ id: groupId, group });
    // CONST
    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]);
    // 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'));
    /**
     * 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.getGroupMembers(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.getGroupMembers(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.GetGroupSubscribers.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 handleRefresh = useMemo(() => (userId) => {
        const newMembers = [...state.results];
        const _updated = newMembers.filter((u) => u.id !== userId);
        dispatch({
            type: actionWidgetTypes.SET_RESULTS,
            payload: { results: newMembers.length > 1 ? _updated : [] }
        });
    }, [dispatch, state.count, state.results]);
    // RENDER
    if ((autoHide && !state.count && state.initialized) || (!contentAvailability && !scUserContext.user) || !scGroup) {
        return _jsx(HiddenPlaceholder, {});
    }
    if (!state.initialized) {
        return _jsx(Skeleton, {});
    }
    const content = (_jsxs(_Fragment, { children: [_jsxs(CardContent, { children: [_jsx(Typography, Object.assign({ className: classes.title, variant: "h5" }, { children: _jsx(FormattedMessage, { id: "ui.groupMembersWidget.title", defaultMessage: "ui.groupMembersWidget.title" }) })), !state.count ? (_jsx(Typography, Object.assign({ className: classes.noResults, variant: "body2" }, { children: _jsx(FormattedMessage, { id: "ui.groupMembersWidget.subtitle.noResults", defaultMessage: "" }) }))) : (_jsxs(React.Fragment, { children: [_jsx(List, { children: state.results.slice(0, state.visibleItems).map((user) => {
                                    var _a, _b;
                                    return (_jsx(ListItem, { children: _jsx(User, { elevation: 0, actions: isGroupAdmin ? (_jsx(GroupSettingsIconButton, { group: scGroup, user: user, onRemoveSuccess: () => handleRefresh(user.id) })) : ((_a = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _a === void 0 ? void 0 : _a.id) !== user.id ? (_jsx(Button, Object.assign({ size: "small", variant: "outlined", component: Link, to: scRoutingContext.url(SCRoutes.USER_PRIVATE_MESSAGES_ROUTE_NAME, user) }, { children: _jsx(FormattedMessage, { id: "ui.groupSettingsIconButton.item.message", defaultMessage: "ui.groupSettingsIconButton.item.message" }) }))) : null, isGroupAdmin: ((_b = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _b === void 0 ? void 0 : _b.id) === user.id, 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.groupMembersWidget.button.showMore", defaultMessage: "ui.groupMembersWidget.button.showMore" }) })))] })), openDialog && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { defaultMessage: "ui.groupMembersWidget.dialogTitle", id: "ui.groupMembersWidget.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.groupMembersWidget.noMoreResults", defaultMessage: "ui.groupMembersWidget.noMoreResults" }) })) }, { children: _jsx(List, { children: state.results.map((user) => {
                                    var _a, _b;
                                    return (_jsx(ListItem, { children: _jsx(User, { elevation: 0, actions: isGroupAdmin ? (_jsx(GroupSettingsIconButton, { group: scGroup, user: user, onRemoveSuccess: () => handleRefresh(user.id) })) : ((_a = scUserContext === null || scUserContext === void 0 ? void 0 : scUserContext.user) === null || _a === void 0 ? void 0 : _a.id) !== user.id ? (_jsx(Button, Object.assign({ size: "small", variant: "outlined", component: Link, to: scRoutingContext.url(SCRoutes.USER_PRIVATE_MESSAGES_ROUTE_NAME, user) }, { children: _jsx(FormattedMessage, { id: "ui.groupSettingsIconButton.item.message", defaultMessage: "ui.groupSettingsIconButton.item.message" }) }))) : null, isGroupAdmin: ((_b = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _b === void 0 ? void 0 : _b.id) === user.id, user: user, userId: user.id }) }, user.id));
                                }) }) })) })))] }), _jsx(CardActions, Object.assign({ className: classes.actions }, { children: _jsx(GroupInviteButton, { groupId: scGroup === null || scGroup === void 0 ? void 0 : scGroup.id, group: scGroup }) }))] }));
    return (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: content })));
}
