import { __rest } from "tslib";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { styled } from '@mui/material/styles';
import { Avatar, Box, Icon, Paper, Typography, useMediaQuery, useTheme } from '@mui/material';
import { SCGroupPrivacyType, SCGroupSubscriptionStatusType } from '@selfcommunity/types';
import { SCPreferences, useSCFetchGroup, useSCPreferences, useSCUser } from '@selfcommunity/react-core';
import GroupHeaderSkeleton from './Skeleton';
import classNames from 'classnames';
import { useThemeProps } from '@mui/system';
import { PREFIX } from './constants';
import ChangeGroupCover from '../ChangeGroupCover';
import { FormattedMessage } from 'react-intl';
import Bullet from '../../shared/Bullet';
import ChangeGroupPicture from '../ChangeGroupPicture';
import GroupMembersButton from '../GroupMembersButton';
import EditGroupButton from '../EditGroupButton';
import GroupSubscribeButton from '../GroupSubscribeButton';
import GroupInviteButton from '../GroupInviteButton';
import { SCGroupEventType, SCTopicType } from '../../constants/PubSub';
import PubSub from 'pubsub-js';
import GroupActionsMenu from '../GroupActionsMenu';
const classes = {
    root: `${PREFIX}-root`,
    cover: `${PREFIX}-cover`,
    avatar: `${PREFIX}-avatar`,
    info: `${PREFIX}-info`,
    name: `${PREFIX}-name`,
    changePicture: `${PREFIX}-change-picture`,
    changeCover: `${PREFIX}-change-cover`,
    visibility: `${PREFIX}-visibility`,
    visibilityItem: `${PREFIX}-visibility-item`,
    members: `${PREFIX}-members`,
    membersCounter: `${PREFIX}-members-counter`,
    multiActions: `${PREFIX}-multi-actions`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'Root'
})(() => ({}));
/**
 * > API documentation for the Community-JS Group Header component. Learn about the available props and the CSS API.
 *
 *
 * This component renders the groups top section.

 #### Import

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

 #### Component Name

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


 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCGroupHeader-root|Styles applied to the root element.|
 |cover|.SCGroupHeader-cover|Styles applied to the cover element.|
 |avatar|.SCGroupHeader-avatar|Styles applied to the avatar element.|
 |info|SCGroupHeader-info|Styles applied to the info section.|
 |name|SCGroupHeader-username|Styles applied to the username element.|
 |changePicture|.SCGroupHeader-change-picture|Styles applied to changePicture element.|
 |changeCover|.SCGroupHeader-change-cover`|Styles applied to changeCover element.|

 * @param inProps
 */
export default function GroupHeader(inProps) {
    var _a;
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { id = null, className = null, group, groupId = null, ChangePictureProps = {}, ChangeCoverProps = {}, GroupSubscribeButtonProps = {}, GroupMembersButtonProps = {}, GroupActionsProps } = props, rest = __rest(props, ["id", "className", "group", "groupId", "ChangePictureProps", "ChangeCoverProps", "GroupSubscribeButtonProps", "GroupMembersButtonProps", "GroupActionsProps"]);
    // PREFERENCES
    const scPreferences = useSCPreferences();
    const visibilityEnabled = useMemo(() => scPreferences.preferences[SCPreferences.CONFIGURATIONS_GROUPS_VISIBILITY_ENABLED].value, [scPreferences.preferences]);
    const privateEnabled = useMemo(() => scPreferences.preferences[SCPreferences.CONFIGURATIONS_GROUPS_PRIVATE_ENABLED].value, [scPreferences.preferences]);
    // CONTEXT
    const scUserContext = useSCUser();
    // HOOKS
    const { scGroup, setSCGroup } = useSCFetchGroup({ id: groupId, group });
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    // REFS
    const updatesSubscription = useRef(null);
    // CONST
    const isGroupAdmin = useMemo(() => { var _a; return scUserContext.user && ((_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id) === scUserContext.user.id; }, [scUserContext.user, (_a = scGroup === null || scGroup === void 0 ? void 0 : scGroup.managed_by) === null || _a === void 0 ? void 0 : _a.id]);
    /**
     * Handles Change Avatar
     * @param avatar
     */
    function handleChangeAvatar(avatar) {
        if (isGroupAdmin) {
            setSCGroup(Object.assign({}, scGroup, { image_big: avatar }));
        }
    }
    /**
     * Handles Change Cover
     * @param cover
     */
    function handleChangeCover(cover) {
        if (isGroupAdmin) {
            setSCGroup(Object.assign({}, scGroup, { emotional_image: cover }));
        }
    }
    /**
     * Handles callback subscribe/unsubscribe group
     */
    const handleSubscribe = (group, status) => {
        setSCGroup(Object.assign(Object.assign({}, group), { subscribers_counter: group.subscribers_counter + (status ? 1 : -1) }));
    };
    /**
     * Subscriber for pubsub callback
     */
    const onChangeGroupMembersHandler = useCallback((msg, data) => {
        var _a;
        if (data && ((_a = data === null || data === void 0 ? void 0 : data.group) === null || _a === void 0 ? void 0 : _a.id) === (scGroup === null || scGroup === void 0 ? void 0 : scGroup.id)) {
            let _group = Object.assign({}, scGroup);
            if (msg === `${SCTopicType.GROUP}.${SCGroupEventType.ADD_MEMBER}`) {
                _group.subscribers_counter = _group.subscribers_counter + 1;
            }
            else if (msg === `${SCTopicType.GROUP}.${SCGroupEventType.REMOVE_MEMBER}`) {
                _group.subscribers_counter = Math.max(_group.subscribers_counter - 1, 0);
            }
            setSCGroup(_group);
        }
    }, [scGroup, setSCGroup]);
    /**
     * On mount, subscribe to receive groups updates (only edit)
     */
    useEffect(() => {
        if (scGroup) {
            updatesSubscription.current = PubSub.subscribe(`${SCTopicType.GROUP}.${SCGroupEventType.MEMBERS}`, onChangeGroupMembersHandler);
        }
        return () => {
            updatesSubscription.current && PubSub.unsubscribe(updatesSubscription.current);
        };
    }, [scGroup]);
    // RENDER
    if (!scGroup) {
        return _jsx(GroupHeaderSkeleton, {});
    }
    const _backgroundCover = Object.assign({}, (scGroup.emotional_image
        ? { background: `url('${scGroup.emotional_image}') center / cover` }
        : { background: `url('${scPreferences.preferences[SCPreferences.IMAGES_USER_DEFAULT_COVER].value}') center / cover` }));
    return (_jsxs(Root, Object.assign({ id: id, className: classNames(classes.root, className) }, rest, { children: [_jsxs(Paper, Object.assign({ style: _backgroundCover, classes: { root: classes.cover } }, { children: [_jsx(Box, Object.assign({ className: classes.avatar }, { children: _jsx(Avatar, { children: _jsx("img", { alt: "group", src: scGroup.image_big ? scGroup.image_big : '' }) }) })), isGroupAdmin && (_jsxs(_Fragment, { children: [_jsx(ChangeGroupPicture, Object.assign({ groupId: scGroup.id, onChange: handleChangeAvatar, className: classes.changePicture }, ChangePictureProps)), _jsx("div", Object.assign({ className: classes.changeCover }, { children: _jsx(ChangeGroupCover, Object.assign({ groupId: scGroup.id, onChange: handleChangeCover }, ChangeCoverProps)) }))] }))] })), _jsxs(Box, Object.assign({ className: classes.info }, { children: [isGroupAdmin && !isMobile && (_jsxs(Box, Object.assign({ className: classes.multiActions }, { children: [_jsx(EditGroupButton, { group: scGroup, groupId: scGroup.id, onEditSuccess: (data) => setSCGroup(data) }), _jsx(GroupActionsMenu, Object.assign({ group: scGroup, onEditSuccess: (data) => setSCGroup(data) }, GroupActionsProps))] }))), _jsx(Typography, Object.assign({ variant: "h5", className: classes.name }, { children: scGroup.name })), privateEnabled && (_jsxs(Box, Object.assign({ className: classes.visibility }, { children: [privateEnabled && (_jsx(_Fragment, { children: scGroup.privacy === SCGroupPrivacyType.PUBLIC ? (_jsxs(Typography, Object.assign({ className: classes.visibilityItem }, { children: [_jsx(Icon, { children: "public" }), _jsx(FormattedMessage, { id: "ui.groupHeader.visibility.public", defaultMessage: "ui.groupHeader.visibility.public" })] }))) : (_jsxs(Typography, Object.assign({ className: classes.visibilityItem }, { children: [_jsx(Icon, { children: "private" }), _jsx(FormattedMessage, { id: "ui.groupHeader.visibility.private", defaultMessage: "ui.groupHeader.visibility.private" })] }))) })), visibilityEnabled && (_jsxs(_Fragment, { children: [privateEnabled && _jsx(Bullet, {}), scGroup.visible ? (_jsxs(Typography, Object.assign({ className: classes.visibilityItem }, { children: [_jsx(Icon, { children: "visibility" }), _jsx(FormattedMessage, { id: "ui.groupHeader.visibility.visible", defaultMessage: "ui.groupHeader.visibility.visible" })] }))) : (_jsxs(Typography, Object.assign({ className: classes.visibilityItem }, { children: [_jsx(Icon, { children: "visibility_off" }), _jsx(FormattedMessage, { id: "ui.groupHeader.visibility.hidden", defaultMessage: "ui.groupHeader.visibility.hidden" })] })))] }))] }))), _jsx(_Fragment, { children: ((scGroup && scGroup.privacy === SCGroupPrivacyType.PUBLIC) ||
                            scGroup.subscription_status === SCGroupSubscriptionStatusType.SUBSCRIBED ||
                            isGroupAdmin) && (_jsxs(Box, Object.assign({ className: classes.members }, { children: [_jsx(Typography, Object.assign({ className: classes.membersCounter, component: "div" }, { children: _jsx(FormattedMessage, { id: "ui.groupHeader.members", defaultMessage: "ui.groupHeader.members", values: { total: scGroup.subscribers_counter } }) })), _jsx(GroupMembersButton, Object.assign({ groupId: scGroup === null || scGroup === void 0 ? void 0 : scGroup.id, group: scGroup, autoHide: !isGroupAdmin }, GroupMembersButtonProps), scGroup.subscribers_counter)] }))) }), isGroupAdmin ? (_jsxs(Box, { children: [_jsx(GroupInviteButton, { group: scGroup, groupId: scGroup.id }), isMobile && _jsx(GroupActionsMenu, Object.assign({ group: scGroup, onEditSuccess: (data) => setSCGroup(data) }, GroupActionsProps))] })) : (_jsx(GroupSubscribeButton, Object.assign({ group: scGroup, onSubscribe: handleSubscribe }, GroupSubscribeButtonProps)))] }))] })));
}
