"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 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 AvatarGroupSkeleton_1 = tslib_1.__importDefault(require("../Skeleton/AvatarGroupSkeleton"));
const User_1 = tslib_1.__importStar(require("../User"));
const PREFIX = 'SCEventParticipantsButton';
const classes = {
    root: `${PREFIX}-root`,
    avatar: `${PREFIX}-avatar`,
    participants: `${PREFIX}-participants`,
    dialogRoot: `${PREFIX}-dialog-root`,
    infiniteScroll: `${PREFIX}-infinite-scroll`,
    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: 'DialogRoot',
    overridesResolver: (_props, styles) => styles.dialogRoot
})(() => ({}));
/**
 *> API documentation for the Community-JS Event Participants Button component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {EventParticipantsButton} from '@selfcommunity/react-ui';
 ```
 #### Component Name

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

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

 * @param inProps
 */
function EventParticipantsButton(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: PREFIX
    });
    const { className, eventId, event, hideCaption = false, DialogProps = {} } = props, rest = tslib_1.__rest(props, ["className", "eventId", "event", "hideCaption", "DialogProps"]);
    // 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 [followers, setFollowers] = (0, react_1.useState)([]);
    const [open, setOpen] = (0, react_1.useState)(false);
    // HOOKS
    const { scEvent } = (0, react_core_1.useSCFetchEvent)({ id: eventId, event });
    const participantsAvailable = (0, react_1.useMemo)(() => scEvent.privacy === types_1.SCEventPrivacyType.PUBLIC ||
        [types_1.SCEventSubscriptionStatusType.SUBSCRIBED, types_1.SCEventSubscriptionStatusType.GOING, types_1.SCEventSubscriptionStatusType.NOT_GOING].indexOf(scEvent.subscription_status) > -1, [scEvent]);
    (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => {
        setFollowers([]);
        setLoading(true);
    }, [scEvent]);
    // FETCH FIRST FOLLOWERS
    (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(() => {
        if (!scEvent) {
            return;
        }
        if (!followers.length && participantsAvailable) {
            api_services_1.EventService.getUsersGoingToEvent(scEvent.id, { limit: 3 }).then((res) => {
                setFollowers([...res.results]);
                setOffset(4);
                setLoading(false);
            });
        }
        else {
            setOffset(0);
        }
    }, [scEvent, participantsAvailable, followers]);
    (0, react_1.useEffect)(() => {
        if (open && offset !== null) {
            setLoading(true);
            api_services_1.EventService.getUsersGoingToEvent(scEvent.id, { offset, limit: 20 }).then((res) => {
                setFollowers([...(offset === 0 ? [] : followers), ...res.results]);
                setNext(res.next);
                setLoading(false);
                setOffset(null);
            });
        }
    }, [open, followers, offset]);
    /**
     * Memoized fetchFollowers
     */
    const fetchFollowers = (0, react_1.useCallback)(() => {
        if (!next) {
            return;
        }
        api_services_1.http
            .request({
            url: next,
            method: api_services_1.Endpoints.GetUsersGoingToEvent.method
        })
            .then((res) => {
            setFollowers([...followers, ...res.data.results]);
            setNext(res.data.next);
        })
            .catch((error) => utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error))
            .then(() => setLoading(false));
    }, [followers, scEvent, next]);
    /**
     * Opens dialog votes
     */
    const handleToggleDialogOpen = (0, react_1.useCallback)(() => {
        setOpen((prev) => !prev);
    }, [setOpen]);
    return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className), onClick: handleToggleDialogOpen, disabled: loading || !scEvent || scEvent.goings_counter === 0 }, rest, { children: [!hideCaption && ((0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.participants, variant: "caption" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { defaultMessage: "ui.eventParticipantsButton.participants", id: "ui.eventParticipantsButton.participants" }) }))), !followers.length && (loading || !scEvent) ? ((0, jsx_runtime_1.jsx)(AvatarGroupSkeleton_1.default, Object.assign({}, rest, (!participantsAvailable && { skeletonsAnimation: false })))) : ((0, jsx_runtime_1.jsx)(material_1.AvatarGroup, Object.assign({ total: followers.length }, { children: followers.map((c) => ((0, jsx_runtime_1.jsx)(material_1.Avatar, { alt: c.username, src: c.avatar, className: classes.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.eventParticipantsButton.dialogTitle", id: "ui.eventParticipantsButton.dialogTitle", values: { total: scEvent.goings_counter } }), onClose: handleToggleDialogOpen, open: open }, DialogProps, { children: (0, jsx_runtime_1.jsx)(InfiniteScroll_1.default, Object.assign({ dataLength: followers.length, next: fetchFollowers, hasMoreNext: next !== null || loading, loaderNext: (0, jsx_runtime_1.jsx)(User_1.UserSkeleton, { elevation: 0 }), className: classes.infiniteScroll, 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.eventParticipantsButton.noOtherParticipants", defaultMessage: "ui.eventParticipantsButton.noOtherParticipants" }) })) }, { children: (0, jsx_runtime_1.jsx)(material_1.List, { children: followers.map((follower) => ((0, jsx_runtime_1.jsx)(material_1.ListItem, { children: (0, jsx_runtime_1.jsx)(User_1.default, { elevation: 0, user: follower }) }, follower.id))) }) })) })))] }));
}
exports.default = EventParticipantsButton;
