import { __rest } from "tslib";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from 'react';
import { styled } from '@mui/material/styles';
import { LoadingButton } from '@mui/lab';
import classNames from 'classnames';
import { useThemeProps } from '@mui/system';
import Icon from '@mui/material/Icon';
import { Avatar, Box, List, ListItem, Tab, Tabs, Typography } from '@mui/material';
import { FormattedMessage } from 'react-intl';
import { useSCFetchVote, useSCUser } from '@selfcommunity/react-core';
import BaseDialog from '../../shared/BaseDialog';
import CentralProgress from '../../shared/CentralProgress';
import InfiniteScroll from '../../shared/InfiniteScroll';
import User from '../User';
const PREFIX = 'SCVoteAudienceButton';
const classes = {
    root: `${PREFIX}-root`,
    reactionList: `${PREFIX}-reaction-list`,
    dialogRoot: `${PREFIX}-dialog-root`,
    dialogTabs: `${PREFIX}-dialog-tabs`,
    dialogVoteBadge: `${PREFIX}-dialog-vote-badge`
};
const Root = styled(LoadingButton, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => [styles.root, styles.voted]
})(({ theme }) => ({}));
const DialogRoot = styled(BaseDialog, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.dialogRoot
})(({ theme }) => ({}));
/**
 * > API documentation for the Community-JS Vote Audience Button component. Learn about the available props and the CSS API.

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCVoteAudienceButton-root|Styles applied to the root element.|
 |reactionList|.SCVoteAudienceButton-reactions|Styles applied to the reactionList list element.|
 |dialogRoot|.SCVoteAudienceButton-dialog-root|Styles applied to the dialog root element.|
 |dialogTabs|.SCVoteAudienceButton-dialog-tabs|Styles applied to the tabs element.|
 |dialogVoteBadge|.SCVoteAudienceButton-dialog-vote-badge|Styles applied to the vote badge element.|
 * @param inProps
 */
export default function VoteAudienceButton(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { className, contributionId, contributionType, contribution = null } = props, rest = __rest(props, ["className", "contributionId", "contributionType", "contribution"]);
    // STATE
    const [open, setOpen] = useState(false);
    const [tab, setTab] = useState(0);
    // CONTEXT
    const scUserContext = useSCUser();
    // HANDLERS
    const handleOpen = (event) => {
        setOpen(true);
    };
    const handleClose = (event) => {
        setOpen(false);
    };
    const handleChangeTab = (event, newValue) => {
        setTab(newValue);
    };
    // HOOKS
    const { isLoading, contributionVoted, contributionVoteCount, contributionReactionsCount, reactions, error, handleFetchVoteList, voteList, isLoadingVoteList, voteListHasNext } = useSCFetchVote({
        id: contributionId,
        contributionType,
        contribution
    });
    // EFFECTS
    useEffect(() => {
        if (!isLoadingVoteList && open) {
            handleFetchVoteList({ reset: true });
        }
    }, [open]);
    useEffect(() => {
        if (isLoadingVoteList || !open) {
            return;
        }
        if (tab === 0) {
            handleFetchVoteList({ reset: true });
            return;
        }
        const { reaction } = contributionReactionsCount[tab - 1];
        handleFetchVoteList({ reaction, reset: true });
    }, [tab]);
    // RENDER
    const audienceIcon = useMemo(() => {
        if (reactions.default && !isLoading && !error) {
            return (_jsx(Box, Object.assign({ className: classes.reactionList }, { children: contributionReactionsCount &&
                    contributionReactionsCount.slice(0, 3).map((count, i) => (_jsx(Icon, { children: _jsx("img", { alt: count.reaction.label, src: count.reaction.image, width: "100%", height: "100%" }) }, count.reaction.id))) })));
        }
        return scUserContext.user && contributionVoted ? _jsx(Icon, { children: "thumb_up" }) : _jsx(Icon, { children: "thumb_up_off_alt" });
    }, [reactions.default, isLoading, error, contributionReactionsCount, scUserContext.user, contributionVoted]);
    const dialogTitle = useMemo(() => {
        if (reactions.default && !isLoading) {
            return (_jsxs(Tabs, Object.assign({ className: classes.dialogTabs, value: tab, onChange: handleChangeTab, "aria-label": "reactions" }, { children: [_jsx(Tab, { label: _jsx(FormattedMessage, { defaultMessage: "ui.voteAudienceButton.dialog.tab.all", id: "ui.voteAudienceButton.dialog.tab.all" }) }), contributionReactionsCount &&
                        contributionReactionsCount.map((count) => (_jsx(Tab, { label: _jsxs(_Fragment, { children: [_jsx(Icon, { children: _jsx("img", { alt: count.reaction.label, src: count.reaction.image, width: "100%", height: "100%" }) }), count.count] }) }, count.reaction.id)))] })));
        }
        else {
            return _jsx(FormattedMessage, { defaultMessage: "ui.voteAudienceButton.dialog.title", id: "ui.voteAudienceButton.dialog.title" });
        }
    }, [tab, reactions, contributionReactionsCount]);
    return (_jsxs(_Fragment, { children: [_jsxs(Root, Object.assign({ onClick: handleOpen, disabled: isLoading || Boolean(error) || contributionVoteCount === 0, loading: isLoading, className: classNames(classes.root, className) }, rest, { children: [audienceIcon, "\u00A0", scUserContext.user && contributionVoted ? (contributionVoteCount === 1 ? (_jsx(FormattedMessage, { id: "ui.voteAudienceButton.votedOnlyByMe", defaultMessage: "ui.voteAudienceButton.votedOnlyByMe" })) : (_jsx(FormattedMessage, { id: "ui.voteAudienceButton.votedByMe", defaultMessage: "ui.voteAudienceButton.votedByMe", values: { total: contributionVoteCount - 1 } }))) : (_jsx(FormattedMessage, { id: "ui.voteAudienceButton.votes", defaultMessage: "ui.voteAudienceButton.votes", values: { total: contributionVoteCount } }))] })), open && (_jsx(DialogRoot, Object.assign({ title: dialogTitle, onClose: handleClose, open: open, DialogContentProps: {} }, { children: isLoadingVoteList && !voteList ? (_jsx(CentralProgress, { size: 50 })) : (_jsx(InfiniteScroll, Object.assign({ dataLength: voteList.length, next: () => handleFetchVoteList({}), hasMoreNext: voteListHasNext, loaderNext: _jsx(CentralProgress, { size: 30 }), height: 400, endMessage: _jsx(Typography, Object.assign({ variant: "body2", align: "center", fontWeight: "bold" }, { children: _jsx(FormattedMessage, { id: "ui.voteAudienceButton.dialog.end", defaultMessage: "ui.voteAudienceButton.dialog.end" }) })) }, { children: _jsx(List, { children: voteList.map((vote) => (_jsx(ListItem, { children: _jsx(User, { elevation: 0, user: vote.user, badgeContent: _jsx(Avatar, Object.assign({ className: classes.dialogVoteBadge }, { children: vote.reaction ? (_jsx(Icon, { children: _jsx("img", { alt: vote.reaction.label, src: vote.reaction.image, width: "100%", height: "100%" }) })) : (_jsx(Icon, { children: "thumb_up" })) })), onClick: handleClose }) }, vote.user.id))) }) }))) })))] }));
}
