import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useMemo, useState } from 'react';
import { FormattedMessage } from 'react-intl';
import TextField from '@mui/material/TextField';
import parse from 'autosuggest-highlight/parse';
import match from 'autosuggest-highlight/match';
import { Autocomplete, Box, Button, DialogTitle, IconButton, Tab, Tabs, Typography } from '@mui/material';
import { styled } from '@mui/material/styles';
import TagChip from '../../../../shared/TagChip';
import classNames from 'classnames';
import Icon from '@mui/material/Icon';
import DialogContent from '@mui/material/DialogContent';
import { SCPreferences, useSCFetchAddressingTagList, useSCPreferences } from '@selfcommunity/react-core';
import { PREFIX } from '../../constants';
import GroupAutocomplete from '../../../GroupAutocomplete';
import { SCFeatureName } from '@selfcommunity/types';
import EventAutocomplete from '../../../EventAutocomplete';
export var AudienceTypes;
(function (AudienceTypes) {
    AudienceTypes["AUDIENCE_ALL"] = "all";
    AudienceTypes["AUDIENCE_TAG"] = "tag";
    AudienceTypes["AUDIENCE_GROUP"] = "group";
    AudienceTypes["AUDIENCE_EVENT"] = "event";
})(AudienceTypes || (AudienceTypes = {}));
const classes = {
    root: `${PREFIX}-layer-audience-root`,
    title: `${PREFIX}-layer-title`,
    content: `${PREFIX}-layer-content`,
    message: `${PREFIX}-layer-audience-message`,
    autocomplete: `${PREFIX}-layer-audience-autocomplete`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'LayerAudienceRoot'
})(() => ({}));
const AudienceLayer = React.forwardRef((props, ref) => {
    // Props
    const { className, onClose, onSave, defaultValue = AudienceTypes.AUDIENCE_TAG ? [] : null, TextFieldProps = {
        variant: 'outlined',
        label: _jsx(FormattedMessage, { id: "ui.composer.layer.audience.tags.label", defaultMessage: "ui.composer.layer.audience.tags.label" })
    } } = props, rest = __rest(props, ["className", "onClose", "onSave", "defaultValue", "TextFieldProps"]);
    // STATE
    const [autocompleteOpen, setAutocompleteOpen] = useState(false);
    const [audience, setAudience] = useState(
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    defaultValue === null || defaultValue.length === 0
        ? AudienceTypes.AUDIENCE_ALL
        : defaultValue && Object.prototype.hasOwnProperty.call(defaultValue, 'recurring')
            ? AudienceTypes.AUDIENCE_EVENT
            : defaultValue && Object.prototype.hasOwnProperty.call(defaultValue, 'managed_by')
                ? AudienceTypes.AUDIENCE_GROUP
                : AudienceTypes.AUDIENCE_TAG);
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const [value, setValue] = useState(defaultValue || undefined);
    // HOOKS
    const { scAddressingTags } = useSCFetchAddressingTagList({ fetch: autocompleteOpen });
    const { preferences, features } = useSCPreferences();
    // MEMO
    const groupsEnabled = useMemo(() => preferences &&
        features &&
        features.includes(SCFeatureName.TAGGING) &&
        features.includes(SCFeatureName.GROUPING) &&
        SCPreferences.CONFIGURATIONS_GROUPS_ENABLED in preferences &&
        preferences[SCPreferences.CONFIGURATIONS_GROUPS_ENABLED].value, [preferences, features]);
    const eventsEnabled = useMemo(() => preferences &&
        features &&
        features.includes(SCFeatureName.TAGGING) &&
        SCPreferences.CONFIGURATIONS_EVENTS_ENABLED in preferences &&
        preferences[SCPreferences.CONFIGURATIONS_EVENTS_ENABLED].value, [preferences, features]);
    // HANDLERS
    const handleSave = useCallback(() => {
        audience === AudienceTypes.AUDIENCE_GROUP || audience === AudienceTypes.AUDIENCE_EVENT
            ? onSave(value)
            : onSave((value === null || value === void 0 ? void 0 : value.length) && (value === null || value === void 0 ? void 0 : value.length) > 0 ? value : null);
    }, [value, onSave, audience]);
    const handleChange = useCallback((event, tags) => setValue(tags), []);
    const handleEventChange = useCallback((event) => setValue(event), []);
    const handleGroupChange = useCallback((group) => setValue(group), []);
    const handleChangeAudience = useCallback((event, data) => setAudience(data), []);
    const handleAutocompleteOpen = useCallback(() => setAutocompleteOpen(true), []);
    const handleAutocompleteClose = useCallback(() => setAutocompleteOpen(false), []);
    return (_jsxs(Root, Object.assign({ ref: ref, className: classNames(className, classes.root) }, rest, { children: [_jsxs(DialogTitle, Object.assign({ className: classes.title }, { children: [_jsx(IconButton, Object.assign({ onClick: onClose }, { children: _jsx(Icon, { children: "arrow_back" }) })), _jsx(Typography, { children: _jsx(FormattedMessage, { id: "ui.composer.layer.audience.title", defaultMessage: "ui.composer.layer.audience.title" }) }), _jsx(Button, Object.assign({ size: "small", color: "secondary", variant: "contained", onClick: handleSave }, { children: _jsx(FormattedMessage, { id: "ui.composer.layer.save", defaultMessage: "ui.composer.layer.save" }) }))] })), _jsxs(DialogContent, Object.assign({ className: classes.content }, { children: [_jsxs(Tabs, Object.assign({ value: audience, onChange: handleChangeAudience, "aria-label": "audience type" }, { children: [_jsx(Tab, { value: AudienceTypes.AUDIENCE_ALL, icon: _jsx(Icon, { children: "public" }), label: _jsx(FormattedMessage, { id: "ui.composer.layer.audience.all", defaultMessage: "ui.composer.layer.audience.all" }) }), eventsEnabled && (_jsx(Tab, { disabled: (Boolean(value === null || value === void 0 ? void 0 : value.length) && !Object.prototype.hasOwnProperty.call(value, 'recurring')) ||
                                    (value !== undefined && Boolean(!(value === null || value === void 0 ? void 0 : value.length)) && audience !== AudienceTypes.AUDIENCE_ALL) ||
                                    (Boolean((value === null || value === void 0 ? void 0 : value.length) === 0) && audience === AudienceTypes.AUDIENCE_ALL && Boolean((defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue.length) !== 0)), value: AudienceTypes.AUDIENCE_EVENT, icon: _jsx(Icon, { children: "CalendarIcon" }), label: _jsx(FormattedMessage, { id: "ui.composer.layer.audience.event", defaultMessage: "ui.composer.layer.audience.event" }) })), groupsEnabled && (_jsx(Tab, { disabled: (Boolean(value === null || value === void 0 ? void 0 : value.length) && !Object.prototype.hasOwnProperty.call(value, 'managed_by')) ||
                                    (value !== undefined && Boolean(!(value === null || value === void 0 ? void 0 : value.length)) && audience !== AudienceTypes.AUDIENCE_ALL) ||
                                    (Boolean((value === null || value === void 0 ? void 0 : value.length) === 0) && audience === AudienceTypes.AUDIENCE_ALL && Boolean((defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue.length) !== 0)), value: AudienceTypes.AUDIENCE_GROUP, icon: _jsx(Icon, { children: "groups" }), label: _jsx(FormattedMessage, { id: "ui.composer.layer.audience.group", defaultMessage: "ui.composer.layer.audience.group" }) })), _jsx(Tab, { disabled: value && Object.prototype.hasOwnProperty.call(value, 'managed_by'), value: AudienceTypes.AUDIENCE_TAG, icon: _jsx(Icon, { children: "label" }), label: _jsx(FormattedMessage, { id: "ui.composer.layer.audience.tag", defaultMessage: "ui.composer.layer.audience.tag" }) })] })), _jsxs(Typography, Object.assign({ className: classes.message }, { children: [audience === AudienceTypes.AUDIENCE_ALL && (_jsx(FormattedMessage, { id: "ui.composer.layer.audience.all.message", defaultMessage: "ui.composer.audience.layer.all.message" })), audience === AudienceTypes.AUDIENCE_EVENT && (_jsx(FormattedMessage, { id: "ui.composer.layer.audience.event.message", defaultMessage: "ui.composer.audience.layer.event.message" })), audience === AudienceTypes.AUDIENCE_GROUP && (_jsx(FormattedMessage, { id: "ui.composer.layer.audience.group.message", defaultMessage: "ui.composer.audience.layer.group.message" })), audience === AudienceTypes.AUDIENCE_TAG && (_jsx(FormattedMessage, { id: "ui.composer.layer.audience.tag.message", defaultMessage: "ui.composer.audience.layer.tag.message" }))] })), audience === AudienceTypes.AUDIENCE_TAG && (_jsx(Autocomplete, { className: classes.autocomplete, open: autocompleteOpen, onOpen: handleAutocompleteOpen, onClose: handleAutocompleteClose, multiple: true, options: scAddressingTags || [], getOptionLabel: (option) => option.name || '', value: value, selectOnFocus: true, clearOnBlur: true, handleHomeEndKeys: true, clearIcon: null, noOptionsText: _jsx(FormattedMessage, { id: "ui.composer.layer.audience.tags.empty", defaultMessage: "ui.composer.layer.audience.tags.empty" }), onChange: handleChange, isOptionEqualToValue: (option, value) => value.id === option.id, renderTags: (value, getTagProps) => {
                            return value.map((option, index) => _jsx(TagChip, Object.assign({ tag: option }, getTagProps({ index })), option.id));
                        }, renderOption: (props, option, { selected, inputValue }) => {
                            const matches = match(option.name, inputValue);
                            const parts = parse(option.name, matches);
                            return (_jsx("li", Object.assign({}, props, { children: _jsx(TagChip, { tag: option, label: _jsx(React.Fragment, { children: parts.map((part, index) => (_jsx("span", Object.assign({ style: { fontWeight: part.highlight ? 700 : 400 } }, { children: part.text }), index))) }) }, option.id) })));
                        }, renderInput: (params) => {
                            return (_jsx(TextField, Object.assign({}, params, TextFieldProps, { InputProps: Object.assign(Object.assign({}, params.InputProps), { autoComplete: 'addressing', endAdornment: _jsx(React.Fragment, { children: params.InputProps.endAdornment }) }) })));
                        } })), audience === AudienceTypes.AUDIENCE_GROUP && _jsx(GroupAutocomplete, { onChange: handleGroupChange, defaultValue: defaultValue }), audience === AudienceTypes.AUDIENCE_EVENT && _jsx(EventAutocomplete, { onChange: handleEventChange, defaultValue: defaultValue })] }))] })));
});
export default AudienceLayer;
