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 { CategoryService, Endpoints, http } from '@selfcommunity/api-services';
import { useSCFetchCategory } from '@selfcommunity/react-core';
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 = 'SCCategoryFollowersButton';
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 Category Followers Button component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {CategoryFollowersButton} from '@selfcommunity/react-ui';
 ```
 #### Component Name

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

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

 * @param inProps
 */
export default function CategoryFollowersButton(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, categoryId, category, DialogProps = {} } = props, rest = __rest(props, ["className", "categoryId", "category", "DialogProps"]);
    // STATE
    const [loading, setLoading] = useState(true);
    const [next, setNext] = useState(null);
    const [offset, setOffset] = useState(null);
    const [followers, setFollowers] = useState([]);
    const [open, setOpen] = useState(false);
    // HOOKS
    const { scCategory } = useSCFetchCategory({ id: categoryId, category });
    // FETCH FIRST FOLLOWERS
    useDeepCompareEffectNoCheck(() => {
        if (!scCategory) {
            return;
        }
        if (followers.length === 0) {
            CategoryService.getCategoryFollowers(scCategory.id, { limit: 3 }).then((res) => {
                setFollowers([...res.results]);
                setOffset(3);
                setLoading(false);
            });
        }
        else {
            setOffset(0);
        }
    }, [scCategory]);
    useEffect(() => {
        if (open && offset !== null) {
            setLoading(true);
            CategoryService.getCategoryFollowers(scCategory.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 = useMemo(() => () => {
        if (!next) {
            return;
        }
        http
            .request({
            url: next,
            method: Endpoints.CategoryFollowers.method
        })
            .then((res) => {
            setFollowers([...followers, ...res.data.results]);
            setNext(res.data.next);
        })
            .catch((error) => Logger.error(SCOPE_SC_UI, error))
            .then(() => setLoading(false));
    }, [followers, scCategory, next]);
    /**
     * Opens dialog votes
     */
    const handleToggleDialogOpen = useMemo(() => () => {
        setOpen((prev) => !prev);
    }, [setOpen]);
    const renderSurplus = useCallback(() => numberFormatter(scCategory.followers_counter), [scCategory]);
    // 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 || !scCategory || scCategory.followers_counter === 0 }, rest, { children: loading || !scCategory ? (_jsx(AvatarGroupSkeleton, Object.assign({}, rest))) : (_jsx(AvatarGroup, Object.assign({ total: scCategory.followers_counter, renderSurplus: renderSurplus }, { children: followers.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.categoryFollowersButton.dialogTitle", id: "ui.categoryFollowersButton.dialogTitle", values: { total: scCategory.followers_counter } }), onClose: handleToggleDialogOpen, open: open }, DialogProps, { children: _jsx(InfiniteScroll, Object.assign({ dataLength: followers.length, next: fetchFollowers, 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.categoryFollowersButton.noOtherFollowers", defaultMessage: "ui.categoryFollowersButton.noOtherFollowers" }) })) }, { children: _jsx(List, { children: followers.map((follower) => (_jsx(ListItem, { children: _jsx(User, { elevation: 0, user: follower }) }, follower.id))) }) })) })))] }));
}
