"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventsChipRoot = void 0;
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 Errors_1 = require("../../constants/Errors");
const Pagination_1 = require("../../constants/Pagination");
const CreateEventButton_1 = tslib_1.__importDefault(require("../CreateEventButton"));
const Event_1 = tslib_1.__importStar(require("../Event"));
const Skeleton_1 = tslib_1.__importDefault(require("../Events/Skeleton"));
const constants_1 = require("./constants");
const PastEventsFilter_1 = tslib_1.__importDefault(require("./PastEventsFilter"));
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const PubSub_1 = require("../../constants/PubSub");
const LocationEventsFilter_1 = tslib_1.__importDefault(require("./LocationEventsFilter"));
const classes = {
    root: `${constants_1.PREFIX}-root`,
    filters: `${constants_1.PREFIX}-filters`,
    events: `${constants_1.PREFIX}-events`,
    item: `${constants_1.PREFIX}-item`,
    itemSkeleton: `${constants_1.PREFIX}-item-skeleton`,
    noResults: `${constants_1.PREFIX}-no-results`,
    showMore: `${constants_1.PREFIX}-show-more`,
    search: `${constants_1.PREFIX}-search`
};
const options = [
    { value: types_1.SCEventDateFilterType.ANY, label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.select.any", defaultMessage: "ui.events.select.any" }) },
    { value: types_1.SCEventDateFilterType.TODAY, label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.select.today", defaultMessage: "ui.events.select.today" }) },
    { value: types_1.SCEventDateFilterType.TOMORROW, label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.select.tomorrow", defaultMessage: "ui.events.select.tomorrow" }) },
    { value: types_1.SCEventDateFilterType.THIS_WEEK, label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.select.thisWeek", defaultMessage: "ui.events.select.thisWeek" }) },
    { value: types_1.SCEventDateFilterType.NEXT_WEEK, label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.select.nextWeek", defaultMessage: "ui.events.select.nextWeek" }) },
    { value: types_1.SCEventDateFilterType.THIS_MONTH, label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.select.thisMonth", defaultMessage: "ui.events.select.thisMonth" }) }
];
const Root = (0, styles_1.styled)(material_1.Box, {
    name: constants_1.PREFIX,
    slot: 'Root'
})(() => ({}));
exports.EventsChipRoot = (0, styles_1.styled)(material_1.Chip, {
    name: constants_1.PREFIX,
    slot: 'EventsChipRoot',
    shouldForwardProp: (prop) => prop !== 'showFollowed' && prop !== 'showPastEvents'
})(() => ({}));
/**
 * > API documentation for the Community-JS Events component. Learn about the available props and the CSS API.
 *
 *
 * The Events component renders the list of all available events.
 * Take a look at our <strong>demo</strong> component [here](/docs/sdk/community-js/react-ui/Components/Events)

 #### Import
 ```jsx
 import {Events} from '@selfcommunity/react-ui';
 ```
 #### Component Name
 The name `SCEvents` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCEvents-root|Styles applied to the root element.|
 |filters|.SCEvents-filters|Styles applied to the title element.|
 |events|.SCEvents-events|Styles applied to the title element.|
 |item|.SCEvents-item|Styles applied to the title element.|
 |noResults|.SCEvents-no-results|Styles applied to no results section.|
 |showMore|.SCEvents-show-more|Styles applied to show more button element.|

 * @param inProps
 */
function Events(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { endpoint = api_services_1.Endpoints.SearchEvents, endpointQueryParams = { limit: 8, offset: Pagination_1.DEFAULT_PAGINATION_OFFSET }, className, EventComponentProps = { elevation: 0, square: true }, EventsSkeletonComponentProps = {}, EventSkeletonComponentProps = { elevation: 0, square: true }, GridContainerComponentProps = {}, GridItemComponentProps = {}, showFilters = false, filters, general = true } = props, rest = tslib_1.__rest(props, ["endpoint", "endpointQueryParams", "className", "EventComponentProps", "EventsSkeletonComponentProps", "EventSkeletonComponentProps", "GridContainerComponentProps", "GridItemComponentProps", "showFilters", "filters", "general"]);
    // STATE
    const [events, setEvents] = (0, react_1.useState)([]);
    const [loading, setLoading] = (0, react_1.useState)(true);
    const [next, setNext] = (0, react_1.useState)(null);
    const [query, setQuery] = (0, react_1.useState)('');
    const [dateSearch, setDateSearch] = (0, react_1.useState)(options[0].value);
    const [location, setLocation] = (0, react_1.useState)(types_1.SCEventLocationFilterType.ANY);
    const [showFollowed, setShowFollowed] = (0, react_1.useState)(false);
    const [showPastEvents, setShowPastEvents] = (0, react_1.useState)(false);
    const [showMyEvents, setShowMyEvents] = (0, react_1.useState)(false);
    // CONTEXT
    const scUserContext = (0, react_1.useContext)(react_core_1.SCUserContext);
    const scPreferencesContext = (0, react_1.useContext)(react_core_1.SCPreferencesContext);
    const onlyStaffEnabled = (0, react_1.useMemo)(() => scPreferencesContext.preferences[react_core_1.SCPreferences.CONFIGURATIONS_EVENTS_ONLY_STAFF_ENABLED].value, [scPreferencesContext.preferences]);
    // MEMO
    const contentAvailability = react_core_1.SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[react_core_1.SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value;
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    // REFS
    const updatesSubscription = (0, react_1.useRef)(null);
    // HANDLERS
    const handleChipClick = () => {
        setShowFollowed(!showFollowed);
    };
    const handleDeleteClick = () => {
        setShowFollowed(false);
    };
    const handleChipPastClick = () => {
        setShowPastEvents(!showPastEvents);
    };
    const handleDeletePastClick = () => {
        setShowPastEvents(false);
    };
    /**
     * Fetches events list
     */
    const fetchEvents = (search) => {
        setLoading(true);
        return api_services_1.http
            .request({
            url: endpoint.url({}),
            method: endpoint.method,
            params: Object.assign(Object.assign({}, endpointQueryParams), (general
                ? Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (search && { search: query })), (dateSearch !== types_1.SCEventDateFilterType.ANY && { date_filter: dateSearch })), (location !== types_1.SCEventLocationFilterType.ANY && { location })), (showFollowed && { follows: showFollowed })), (showPastEvents && { date_filter: types_1.SCEventDateFilterType.PAST })) : Object.assign(Object.assign(Object.assign({ subscription_status: types_1.SCEventSubscriptionStatusType.GOING }, (location !== types_1.SCEventLocationFilterType.ANY && { location })), (showPastEvents && { past: showPastEvents })), (showMyEvents && { created_by: authUserId }))))
        })
            .then((res) => {
            setEvents(res.data.results);
            setNext(res.data.next);
            setLoading(false);
        })
            .catch((error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
        });
    };
    /**
     * On mount, fetches events list
     */
    (0, react_1.useEffect)(() => {
        if (!contentAvailability && !authUserId) {
            return;
        }
        else {
            query === '' && fetchEvents();
        }
    }, [contentAvailability, authUserId, dateSearch, location, showFollowed, showPastEvents, showMyEvents, query]);
    /**
     * Subscriber for pubsub callback
     */
    const onDeleteEventHandler = (0, react_1.useCallback)((_msg, deleted) => {
        setEvents((prev) => {
            if (prev.some((e) => e.id === deleted)) {
                return prev.filter((e) => e.id !== deleted);
            }
            return prev;
        });
    }, [events]);
    /**
     * On mount, subscribe to receive event updates (only delete)
     */
    (0, react_1.useEffect)(() => {
        if (events) {
            updatesSubscription.current = pubsub_js_1.default.subscribe(`${PubSub_1.SCTopicType.EVENT}.${PubSub_1.SCGroupEventType.DELETE}`, onDeleteEventHandler);
        }
        return () => {
            updatesSubscription.current && pubsub_js_1.default.unsubscribe(updatesSubscription.current);
        };
    }, [events]);
    const handleNext = (0, react_1.useMemo)(() => () => {
        if (!next) {
            return;
        }
        return api_services_1.http
            .request({
            url: next,
            method: general ? api_services_1.Endpoints.SearchEvents.method : api_services_1.Endpoints.GetUserEvents.method
        })
            .then((res) => {
            setEvents([...events, ...res.data.results]);
            setNext(res.data.next);
        })
            .catch((error) => console.log(error))
            .then(() => setLoading(false));
    }, [next]);
    /**
     * Handle change filter name
     * @param event
     */
    const handleOnChangeFilterName = (event) => {
        setQuery(event.target.value);
    };
    /**
     * Handle change time frame
     * @param event
     */
    const handleOnChangeTimeFrame = (event) => {
        setDateSearch(event.target.value);
    };
    /**
     * Handle change location
     * @param event
     */
    const handleOnChangeLocation = (event) => {
        setLocation(event.target.value);
    };
    /**
     * Renders events list
     */
    const c = ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [showFilters && ((0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ container: true, className: classes.filters, gap: 2 }, { children: filters ? (filters) : !general ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(events.length !== 0 || (events.length === 0 && showMyEvents)) && ((0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true }, { children: (0, jsx_runtime_1.jsx)(exports.EventsChipRoot
                            // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                            // @ts-ignore
                            , { 
                                // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                                // @ts-ignore
                                color: showMyEvents ? 'secondary' : 'default', 
                                // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                                // @ts-ignore
                                variant: showMyEvents ? 'filled' : 'outlined', label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.filterByCreatedByMe", defaultMessage: "ui.events.filterByCreatedByMe" }), onClick: () => setShowMyEvents(!showMyEvents), 
                                // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                                // @ts-ignore
                                showFollowed: showMyEvents, deleteIcon: showMyEvents ? (0, jsx_runtime_1.jsx)(material_1.Icon, { children: "close" }) : null, onDelete: showMyEvents ? handleDeleteClick : null, autoHide: !loading && !events.length, disabled: loading }) }))), (0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true }, { children: (0, jsx_runtime_1.jsx)(PastEventsFilter_1.default, { showPastEvents: showPastEvents, handleClick: handleChipPastClick, handleDeleteClick: handleDeletePastClick, autoHide: !loading && !events.length && !showPastEvents, disabled: loading }) })), (0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: (0, jsx_runtime_1.jsx)(LocationEventsFilter_1.default, { value: location, autoHide: !loading && !events.length, disabled: loading || (!events.length && !location), handleOnChange: handleOnChangeLocation }) }))] })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true, xs: 12, md: 3 }, { children: (0, jsx_runtime_1.jsx)(material_1.TextField, { className: classes.search, size: 'small', fullWidth: true, value: query, label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.filterByName", defaultMessage: "ui.events.filterByName" }), variant: "outlined", onChange: handleOnChangeFilterName, disabled: loading || (!events.length && !query), onKeyUp: (e) => {
                                    e.preventDefault();
                                    if (e.key === 'Enter') {
                                        fetchEvents(true);
                                    }
                                }, InputProps: {
                                    endAdornment: ((0, jsx_runtime_1.jsx)(material_1.InputAdornment, Object.assign({ position: "end" }, { children: isMobile ? ((0, jsx_runtime_1.jsx)(material_1.IconButton, Object.assign({ onClick: () => fetchEvents(true), disabled: loading || (!events.length && !query) }, { children: (0, jsx_runtime_1.jsx)(material_1.Icon, { children: "search" }) }))) : ((0, jsx_runtime_1.jsx)(material_1.Button, { size: "small", variant: "contained", color: "secondary", onClick: () => fetchEvents(true), endIcon: (0, jsx_runtime_1.jsx)(material_1.Icon, { children: "search" }), disabled: loading || (!events.length && !query) })) })))
                                } }) })), (0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: (0, jsx_runtime_1.jsxs)(material_1.FormControl, Object.assign({ fullWidth: true }, { children: [(0, jsx_runtime_1.jsx)(material_1.InputLabel, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.filterByDate", defaultMessage: "ui.events.filterByDate" }) }), (0, jsx_runtime_1.jsx)(material_1.Select, Object.assign({ disabled: showPastEvents || loading || (!events.length && dateSearch === types_1.SCEventDateFilterType.ANY), size: 'small', label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.filterByDate", defaultMessage: "ui.events.filterByDate" }), value: dateSearch, onChange: handleOnChangeTimeFrame, renderValue: (selected) => options.find((option) => option.value === selected).label }, { children: options.map((option) => ((0, jsx_runtime_1.jsxs)(material_1.MenuItem, Object.assign({ value: option.value }, { children: [(0, jsx_runtime_1.jsx)(material_1.Radio, { checked: dateSearch === option.value, value: option.value, name: "radio-button-select", inputProps: { 'aria-label': option.label } }), option.label] }), option.value))) }))] })) })), (0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: (0, jsx_runtime_1.jsx)(LocationEventsFilter_1.default, { value: location, disabled: loading || (!events.length && !location), handleOnChange: handleOnChangeLocation }) })), authUserId && ((0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true }, { children: (0, jsx_runtime_1.jsx)(exports.EventsChipRoot
                            // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                            // @ts-ignore
                            , { 
                                // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                                // @ts-ignore
                                color: showFollowed ? 'secondary' : 'default', 
                                // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                                // @ts-ignore
                                variant: showFollowed ? 'filled' : 'outlined', label: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.filterByFollowedInterest", defaultMessage: "ui.events.filterByFollowedInterest" }), onClick: handleChipClick, 
                                // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
                                // @ts-ignore
                                showFollowed: showFollowed, deleteIcon: showFollowed ? (0, jsx_runtime_1.jsx)(material_1.Icon, { children: "close" }) : null, onDelete: showFollowed ? handleDeleteClick : null, disabled: loading || (!events.length && !showFollowed) }) }))), (0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true }, { children: (0, jsx_runtime_1.jsx)(PastEventsFilter_1.default, { showPastEvents: showPastEvents, handleClick: handleChipPastClick, handleDeleteClick: handleDeletePastClick, disabled: dateSearch !== types_1.SCEventDateFilterType.ANY || loading || (!events.length && !showPastEvents) }) }))] })) }))), (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: loading ? ((0, jsx_runtime_1.jsx)(Skeleton_1.default, Object.assign({}, EventsSkeletonComponentProps, { EventSkeletonProps: EventSkeletonComponentProps }))) : ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: !events.length ? ((0, jsx_runtime_1.jsx)(material_1.Box, Object.assign({ className: classes.noResults }, { children: (onlyStaffEnabled && !react_core_1.UserUtils.isStaff(scUserContext.user)) ||
                            (onlyStaffEnabled && react_core_1.UserUtils.isStaff(scUserContext.user) && general) ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Event_1.EventSkeleton, Object.assign({}, EventSkeletonComponentProps)), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "body1" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.noEvents.title", defaultMessage: "ui.events.noEvents.title" }) }))] })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Event_1.EventSkeleton, Object.assign({}, EventSkeletonComponentProps, { skeletonsAnimation: false, actions: (0, jsx_runtime_1.jsx)(CreateEventButton_1.default, {}) })), (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "body1" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.noEvents.title.onlyStaff", defaultMessage: "ui.events.noEvents.title.onlyStaff" }) }))] })) }))) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ container: true, spacing: { xs: 2 }, className: classes.events }, GridContainerComponentProps, { children: (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [events.map((event) => ((0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true, xs: 12, sm: 12, md: 6, className: classes.item }, GridItemComponentProps, { children: (0, jsx_runtime_1.jsx)(Event_1.default, Object.assign({ event: event, eventId: event.id }, EventComponentProps)) }), event.id))), authUserId && events.length % 2 !== 0 && ((0, jsx_runtime_1.jsx)(material_1.Grid, Object.assign({ item: true, xs: 12, sm: 12, md: 6, className: classes.itemSkeleton }, GridItemComponentProps, { children: (0, jsx_runtime_1.jsx)(Event_1.EventSkeleton, Object.assign({}, EventSkeletonComponentProps, { skeletonsAnimation: false, actions: (0, jsx_runtime_1.jsx)(CreateEventButton_1.default, Object.assign({ variant: "outlined", color: "primary", size: "small" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.skeleton.action.add", defaultMessage: "ui.events.skeleton.action.add" }) })) })) }), 'skeleton-item'))] }) })), Boolean(next) && ((0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ color: "secondary", variant: "text", onClick: handleNext, className: classes.showMore }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.events.button.seeMore", defaultMessage: "ui.events.button.seeMore" }) })))] })) })) })] }));
    /**
     * Renders root object (if content availability community option is false and user is anonymous, component is hidden)
     */
    if (!contentAvailability && !scUserContext.user) {
        return null;
    }
    return ((0, jsx_runtime_1.jsx)(Root, Object.assign({ className: (0, classnames_1.default)(classes.root, className) }, rest, { children: c })));
}
exports.default = Events;
