"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const material_1 = require("@mui/material");
const styles_1 = require("@mui/material/styles");
const useMediaQuery_1 = tslib_1.__importDefault(require("@mui/material/useMediaQuery"));
const system_1 = require("@mui/system");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
const types_1 = require("@selfcommunity/types");
const utils_1 = require("@selfcommunity/utils");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const react_1 = require("react");
const react_intl_1 = require("react-intl");
const use_deep_compare_effect_1 = require("use-deep-compare-effect");
const Errors_1 = require("../../constants/Errors");
const BaseDialog_1 = tslib_1.__importDefault(require("../../shared/BaseDialog"));
const InfiniteScroll_1 = tslib_1.__importDefault(require("../../shared/InfiniteScroll"));
const buttonCounters_1 = require("../../utils/buttonCounters");
const AvatarGroupSkeleton_1 = tslib_1.__importDefault(require("../Skeleton/AvatarGroupSkeleton"));
const User_1 = tslib_1.__importStar(require("../User"));
const PREFIX = 'SCGroupMembersButton';
const classes = {
    root: `${PREFIX}-root`,
    dialogRoot: `${PREFIX}-dialog-root`,
    endMessage: `${PREFIX}-end-message`
};
const Root = (0, styles_1.styled)(material_1.Button, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root
})(() => ({}));
const DialogRoot = (0, styles_1.styled)(BaseDialog_1.default, {
    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
 */
function GroupMembersButton(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className, groupId, group, DialogProps = {}, autoHide = false } = props, rest = tslib_1.__rest(props, ["className", "groupId", "group", "DialogProps", "autoHide"]);
    // STATE
    const [loading, setLoading] = (0, react_1.useState)(true);
    const [next, setNext] = (0, react_1.useState)(null);
    const [offset, setOffset] = (0, react_1.useState)(null);
    const [members, setMembers] = (0, react_1.useState)([]);
    const [open, setOpen] = (0, react_1.useState)(false);
    // HOOKS
    const { scGroup } = (0, react_core_1.useSCFetchGroup)({ id: groupId, group });
    // FETCH FIRST FOLLOWERS
    (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => {
        if (!scGroup ||
            (scGroup &&
                scGroup.privacy !== types_1.SCGroupPrivacyType.PUBLIC &&
                scGroup.subscription_status !== types_1.SCGroupSubscriptionStatusType.SUBSCRIBED &&
                autoHide)) {
            return;
        }
        if (members.length === 0) {
            api_services_1.GroupService.getGroupMembers(scGroup.id, { limit: 3 }).then((res) => {
                setMembers([...res.results]);
                setOffset(3);
                setLoading(false);
            });
        }
        else {
            setOffset(0);
        }
    }, [scGroup]);
    (0, react_1.useEffect)(() => {
        if (open && offset !== null) {
            setLoading(true);
            api_services_1.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 = (0, react_1.useMemo)(() => () => {
        if (!next) {
            return;
        }
        api_services_1.http
            .request({
            url: next,
            method: api_services_1.Endpoints.GetGroupSubscribers.method
        })
            .then((res) => {
            setMembers([...members, ...res.data.results]);
            setNext(res.data.next);
        })
            .catch((error) => utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error))
            .then(() => setLoading(false));
    }, [members, scGroup, next]);
    /**
     * Opens dialog votes
     */
    const handleToggleDialogOpen = (0, react_1.useMemo)(() => () => {
        setOpen((prev) => !prev);
    }, [setOpen]);
    const renderSurplus = (0, react_1.useCallback)(() => (0, buttonCounters_1.numberFormatter)(scGroup.subscribers_counter), [scGroup]);
    // RENDER
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, useMediaQuery_1.default)(theme.breakpoints.down('md'));
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className), onClick: handleToggleDialogOpen, disabled: loading || !scGroup || scGroup.subscribers_counter === 0 }, rest, { children: loading || !scGroup ? ((0, jsx_runtime_1.jsx)(AvatarGroupSkeleton_1.default, Object.assign({}, rest))) : ((0, jsx_runtime_1.jsx)(material_1.AvatarGroup, Object.assign({ total: scGroup.subscribers_counter, renderSurplus: renderSurplus }, { children: members.map((c) => ((0, jsx_runtime_1.jsx)(material_1.Avatar, { alt: c.username, src: c.avatar }, c.id))) }))) })), open && ((0, jsx_runtime_1.jsx)(DialogRoot, Object.assign({ className: classes.dialogRoot, title: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.groupMembersButton.dialogTitle", id: "ui.groupMembersButton.dialogTitle", values: { total: scGroup.subscribers_counter } }), onClose: handleToggleDialogOpen, open: open }, DialogProps, { children: (0, jsx_runtime_1.jsx)(InfiniteScroll_1.default, Object.assign({ dataLength: members.length, next: fetchMembers, hasMoreNext: next !== null || loading, loaderNext: (0, jsx_runtime_1.jsx)(User_1.UserSkeleton, { elevation: 0 }), height: isMobile ? '100%' : 400, endMessage: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.endMessage }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.groupMembersButton.noOtherMembers", defaultMessage: "ui.groupMembersButton.noOtherMembers" }) })) }, { children: (0, jsx_runtime_1.jsx)(material_1.List, { children: members.map((member) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(User_1.default, { elevation: 0, user: member, onClick: handleToggleDialogOpen }) }, member.id))) }) })) })))] }));
}
exports.default = GroupMembersButton;
