import { __rest } from "tslib";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { Avatar, AvatarGroup, Button, List, ListItem, Typography, useTheme } from '@mui/material';
import { styled } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useThemeProps } from '@mui/system';
import { Endpoints, GroupService, http } from '@selfcommunity/api-services';
import { useSCFetchGroup } from '@selfcommunity/react-core';
import { SCGroupPrivacyType, SCGroupSubscriptionStatusType } from '@selfcommunity/types';
import { Logger } from '@selfcommunity/utils';
import classNames from 'classnames';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { FormattedMessage } from 'react-intl';
import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect';
import { SCOPE_SC_UI } from '../../constants/Errors';
import BaseDialog from '../../shared/BaseDialog';
import InfiniteScroll from '../../shared/InfiniteScroll';
import { numberFormatter } from '../../utils/buttonCounters';
import AvatarGroupSkeleton from '../Skeleton/AvatarGroupSkeleton';
import User, { UserSkeleton } from '../User';
const PREFIX = 'SCGroupMembersButton';
const classes = {
    root: `${PREFIX}-root`,
    dialogRoot: `${PREFIX}-dialog-root`,
    endMessage: `${PREFIX}-end-message`
};
const Root = styled(Button, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root
})(() => ({}));
const DialogRoot = styled(BaseDialog, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.dialogRoot
})(() => ({}));
/**
 *> API documentation for the Community-JS Group Members Button component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {GroupMembersButton} from '@selfcommunity/react-ui';
 ```
 #### Component Name

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

 * #### CSS
 *
 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCGroupMembersButton-root|Styles applied to the root element.|
 |dialogRoot|.SCGroupMembersButton-dialog-root|Styles applied to the root element.|
 |endMessage|.SCCategoriesFollowedWidget-end-message|Styles applied to the end message element.|

 * @param inProps
 */
export default function GroupMembersButton(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, groupId, group, DialogProps = {}, autoHide = false } = props, rest = __rest(props, ["className", "groupId", "group", "DialogProps", "autoHide"]);
    // STATE
    const [loading, setLoading] = useState(true);
    const [next, setNext] = useState(null);
    const [offset, setOffset] = useState(null);
    const [members, setMembers] = useState([]);
    const [open, setOpen] = useState(false);
    // HOOKS
    const { scGroup } = useSCFetchGroup({ id: groupId, group });
    // FETCH FIRST FOLLOWERS
    useDeepCompareEffectNoCheck(() => {
        if (!scGroup ||
            (scGroup &&
                scGroup.privacy !== SCGroupPrivacyType.PUBLIC &&
                scGroup.subscription_status !== SCGroupSubscriptionStatusType.SUBSCRIBED &&
                autoHide)) {
            return;
        }
        if (members.length === 0) {
            GroupService.getGroupMembers(scGroup.id, { limit: 3 }).then((res) => {
                setMembers([...res.results]);
                setOffset(3);
                setLoading(false);
            });
        }
        else {
            setOffset(0);
        }
    }, [scGroup]);
    useEffect(() => {
        if (open && offset !== null) {
            setLoading(true);
            GroupService.getGroupMembers(scGroup.id, { offset, limit: 20 }).then((res) => {
                setMembers([...(offset === 0 ? [] : members), ...res.results]);
                setNext(res.next);
                setLoading(false);
                setOffset(null);
            });
        }
    }, [open, members, offset]);
    /**
     * Memoized fetchMembers
     */
    const fetchMembers = useMemo(() => () => {
        if (!next) {
            return;
        }
        http
            .request({
            url: next,
            method: Endpoints.GetGroupSubscribers.method
        })
            .then((res) => {
            setMembers([...members, ...res.data.results]);
            setNext(res.data.next);
        })
            .catch((error) => Logger.error(SCOPE_SC_UI, error))
            .then(() => setLoading(false));
    }, [members, scGroup, next]);
    /**
     * Opens dialog votes
     */
    const handleToggleDialogOpen = useMemo(() => () => {
        setOpen((prev) => !prev);
    }, [setOpen]);
    const renderSurplus = useCallback(() => numberFormatter(scGroup.subscribers_counter), [scGroup]);
    // RENDER
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    return (_jsxs(_Fragment, { children: [_jsx(Root, Object.assign({ className: classNames(classes.root, className), onClick: handleToggleDialogOpen, disabled: loading || !scGroup || scGroup.subscribers_counter === 0 }, rest, { children: loading || !scGroup ? (_jsx(AvatarGroupSkeleton, Object.assign({}, rest))) : (_jsx(AvatarGroup, Object.assign({ total: scGroup.subscribers_counter, renderSurplus: renderSurplus }, { children: members.map((c) => (_jsx(Avatar, { alt: c.username, src: c.avatar }, c.id))) }))) })), open && (_jsx(DialogRoot, Object.assign({ className: classes.dialogRoot, title: _jsx(FormattedMessage, { defaultMessage: "ui.groupMembersButton.dialogTitle", id: "ui.groupMembersButton.dialogTitle", values: { total: scGroup.subscribers_counter } }), onClose: handleToggleDialogOpen, open: open }, DialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: members.length, next: fetchMembers, hasMoreNext: next !== null || loading, loaderNext: _jsx(UserSkeleton, { elevation: 0 }), height: isMobile ? '100%' : 400, endMessage: _jsx(Typography, Object.assign({ className: classes.endMessage }, { children: _jsx(FormattedMessage, { id: "ui.groupMembersButton.noOtherMembers", defaultMessage: "ui.groupMembersButton.noOtherMembers" }) })) }, { children: _jsx(List, { children: members.map((member) => (_jsx(ListItem, { children: _jsx(User, { elevation: 0, user: member, onClick: handleToggleDialogOpen }) }, member.id))) }) })) })))] }));
}
