import { __rest } from "tslib";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { Box, Button, Chip, FormControl, Grid, Icon, IconButton, InputAdornment, InputLabel, MenuItem, Radio, Select, TextField, Typography, useMediaQuery, useTheme } from '@mui/material';
import { styled } from '@mui/material/styles';
import { useThemeProps } from '@mui/system';
import { Endpoints, http } from '@selfcommunity/api-services';
import { SCPreferences, SCPreferencesContext, SCUserContext, UserUtils } from '@selfcommunity/react-core';
import { SCEventDateFilterType, SCEventSubscriptionStatusType, SCEventLocationFilterType } from '@selfcommunity/types';
import { Logger } from '@selfcommunity/utils';
import classNames from 'classnames';
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { FormattedMessage } from 'react-intl';
import { SCOPE_SC_UI } from '../../constants/Errors';
import { DEFAULT_PAGINATION_OFFSET } from '../../constants/Pagination';
import CreateEventButton from '../CreateEventButton';
import Event, { EventSkeleton } from '../Event';
import Skeleton from '../Events/Skeleton';
import { PREFIX } from './constants';
import PastEventsFilter from './PastEventsFilter';
import PubSub from 'pubsub-js';
import { SCGroupEventType, SCTopicType } from '../../constants/PubSub';
import LocationEventsFilter from './LocationEventsFilter';
const classes = {
    root: `${PREFIX}-root`,
    filters: `${PREFIX}-filters`,
    events: `${PREFIX}-events`,
    item: `${PREFIX}-item`,
    itemSkeleton: `${PREFIX}-item-skeleton`,
    noResults: `${PREFIX}-no-results`,
    showMore: `${PREFIX}-show-more`,
    search: `${PREFIX}-search`
};
const options = [
    { value: SCEventDateFilterType.ANY, label: _jsx(FormattedMessage, { id: "ui.events.select.any", defaultMessage: "ui.events.select.any" }) },
    { value: SCEventDateFilterType.TODAY, label: _jsx(FormattedMessage, { id: "ui.events.select.today", defaultMessage: "ui.events.select.today" }) },
    { value: SCEventDateFilterType.TOMORROW, label: _jsx(FormattedMessage, { id: "ui.events.select.tomorrow", defaultMessage: "ui.events.select.tomorrow" }) },
    { value: SCEventDateFilterType.THIS_WEEK, label: _jsx(FormattedMessage, { id: "ui.events.select.thisWeek", defaultMessage: "ui.events.select.thisWeek" }) },
    { value: SCEventDateFilterType.NEXT_WEEK, label: _jsx(FormattedMessage, { id: "ui.events.select.nextWeek", defaultMessage: "ui.events.select.nextWeek" }) },
    { value: SCEventDateFilterType.THIS_MONTH, label: _jsx(FormattedMessage, { id: "ui.events.select.thisMonth", defaultMessage: "ui.events.select.thisMonth" }) }
];
const Root = styled(Box, {
    name: PREFIX,
    slot: 'Root'
})(() => ({}));
export const EventsChipRoot = styled(Chip, {
    name: 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
 */
export default function Events(inProps) {
    // PROPS
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    const { endpoint = Endpoints.SearchEvents, endpointQueryParams = { limit: 8, offset: DEFAULT_PAGINATION_OFFSET }, className, EventComponentProps = { elevation: 0, square: true }, EventsSkeletonComponentProps = {}, EventSkeletonComponentProps = { elevation: 0, square: true }, GridContainerComponentProps = {}, GridItemComponentProps = {}, showFilters = false, filters, general = true } = props, rest = __rest(props, ["endpoint", "endpointQueryParams", "className", "EventComponentProps", "EventsSkeletonComponentProps", "EventSkeletonComponentProps", "GridContainerComponentProps", "GridItemComponentProps", "showFilters", "filters", "general"]);
    // STATE
    const [events, setEvents] = useState([]);
    const [loading, setLoading] = useState(true);
    const [next, setNext] = useState(null);
    const [query, setQuery] = useState('');
    const [dateSearch, setDateSearch] = useState(options[0].value);
    const [location, setLocation] = useState(SCEventLocationFilterType.ANY);
    const [showFollowed, setShowFollowed] = useState(false);
    const [showPastEvents, setShowPastEvents] = useState(false);
    const [showMyEvents, setShowMyEvents] = useState(false);
    // CONTEXT
    const scUserContext = useContext(SCUserContext);
    const scPreferencesContext = useContext(SCPreferencesContext);
    const onlyStaffEnabled = useMemo(() => scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_EVENTS_ONLY_STAFF_ENABLED].value, [scPreferencesContext.preferences]);
    // MEMO
    const contentAvailability = SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY in scPreferencesContext.preferences &&
        scPreferencesContext.preferences[SCPreferences.CONFIGURATIONS_CONTENT_AVAILABILITY].value;
    // CONST
    const authUserId = scUserContext.user ? scUserContext.user.id : null;
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    // REFS
    const updatesSubscription = 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 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 !== SCEventDateFilterType.ANY && { date_filter: dateSearch })), (location !== SCEventLocationFilterType.ANY && { location })), (showFollowed && { follows: showFollowed })), (showPastEvents && { date_filter: SCEventDateFilterType.PAST })) : Object.assign(Object.assign(Object.assign({ subscription_status: SCEventSubscriptionStatusType.GOING }, (location !== SCEventLocationFilterType.ANY && { location })), (showPastEvents && { past: showPastEvents })), (showMyEvents && { created_by: authUserId }))))
        })
            .then((res) => {
            setEvents(res.data.results);
            setNext(res.data.next);
            setLoading(false);
        })
            .catch((error) => {
            Logger.error(SCOPE_SC_UI, error);
        });
    };
    /**
     * On mount, fetches events list
     */
    useEffect(() => {
        if (!contentAvailability && !authUserId) {
            return;
        }
        else {
            query === '' && fetchEvents();
        }
    }, [contentAvailability, authUserId, dateSearch, location, showFollowed, showPastEvents, showMyEvents, query]);
    /**
     * Subscriber for pubsub callback
     */
    const onDeleteEventHandler = 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)
     */
    useEffect(() => {
        if (events) {
            updatesSubscription.current = PubSub.subscribe(`${SCTopicType.EVENT}.${SCGroupEventType.DELETE}`, onDeleteEventHandler);
        }
        return () => {
            updatesSubscription.current && PubSub.unsubscribe(updatesSubscription.current);
        };
    }, [events]);
    const handleNext = useMemo(() => () => {
        if (!next) {
            return;
        }
        return http
            .request({
            url: next,
            method: general ? Endpoints.SearchEvents.method : 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 = (_jsxs(_Fragment, { children: [showFilters && (_jsx(Grid, Object.assign({ container: true, className: classes.filters, gap: 2 }, { children: filters ? (filters) : !general ? (_jsxs(_Fragment, { children: [(events.length !== 0 || (events.length === 0 && showMyEvents)) && (_jsx(Grid, Object.assign({ item: true }, { children: _jsx(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: _jsx(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 ? _jsx(Icon, { children: "close" }) : null, onDelete: showMyEvents ? handleDeleteClick : null, autoHide: !loading && !events.length, disabled: loading }) }))), _jsx(Grid, Object.assign({ item: true }, { children: _jsx(PastEventsFilter, { showPastEvents: showPastEvents, handleClick: handleChipPastClick, handleDeleteClick: handleDeletePastClick, autoHide: !loading && !events.length && !showPastEvents, disabled: loading }) })), _jsx(Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: _jsx(LocationEventsFilter, { value: location, autoHide: !loading && !events.length, disabled: loading || (!events.length && !location), handleOnChange: handleOnChangeLocation }) }))] })) : (_jsxs(_Fragment, { children: [_jsx(Grid, Object.assign({ item: true, xs: 12, md: 3 }, { children: _jsx(TextField, { className: classes.search, size: 'small', fullWidth: true, value: query, label: _jsx(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: (_jsx(InputAdornment, Object.assign({ position: "end" }, { children: isMobile ? (_jsx(IconButton, Object.assign({ onClick: () => fetchEvents(true), disabled: loading || (!events.length && !query) }, { children: _jsx(Icon, { children: "search" }) }))) : (_jsx(Button, { size: "small", variant: "contained", color: "secondary", onClick: () => fetchEvents(true), endIcon: _jsx(Icon, { children: "search" }), disabled: loading || (!events.length && !query) })) })))
                                } }) })), _jsx(Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: _jsxs(FormControl, Object.assign({ fullWidth: true }, { children: [_jsx(InputLabel, { children: _jsx(FormattedMessage, { id: "ui.events.filterByDate", defaultMessage: "ui.events.filterByDate" }) }), _jsx(Select, Object.assign({ disabled: showPastEvents || loading || (!events.length && dateSearch === SCEventDateFilterType.ANY), size: 'small', label: _jsx(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) => (_jsxs(MenuItem, Object.assign({ value: option.value }, { children: [_jsx(Radio, { checked: dateSearch === option.value, value: option.value, name: "radio-button-select", inputProps: { 'aria-label': option.label } }), option.label] }), option.value))) }))] })) })), _jsx(Grid, Object.assign({ item: true, xs: 12, md: 2 }, { children: _jsx(LocationEventsFilter, { value: location, disabled: loading || (!events.length && !location), handleOnChange: handleOnChangeLocation }) })), authUserId && (_jsx(Grid, Object.assign({ item: true }, { children: _jsx(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: _jsx(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 ? _jsx(Icon, { children: "close" }) : null, onDelete: showFollowed ? handleDeleteClick : null, disabled: loading || (!events.length && !showFollowed) }) }))), _jsx(Grid, Object.assign({ item: true }, { children: _jsx(PastEventsFilter, { showPastEvents: showPastEvents, handleClick: handleChipPastClick, handleDeleteClick: handleDeletePastClick, disabled: dateSearch !== SCEventDateFilterType.ANY || loading || (!events.length && !showPastEvents) }) }))] })) }))), _jsx(_Fragment, { children: loading ? (_jsx(Skeleton, Object.assign({}, EventsSkeletonComponentProps, { EventSkeletonProps: EventSkeletonComponentProps }))) : (_jsx(_Fragment, { children: !events.length ? (_jsx(Box, Object.assign({ className: classes.noResults }, { children: (onlyStaffEnabled && !UserUtils.isStaff(scUserContext.user)) ||
                            (onlyStaffEnabled && UserUtils.isStaff(scUserContext.user) && general) ? (_jsxs(_Fragment, { children: [_jsx(EventSkeleton, Object.assign({}, EventSkeletonComponentProps)), _jsx(Typography, Object.assign({ variant: "body1" }, { children: _jsx(FormattedMessage, { id: "ui.events.noEvents.title", defaultMessage: "ui.events.noEvents.title" }) }))] })) : (_jsxs(_Fragment, { children: [_jsx(EventSkeleton, Object.assign({}, EventSkeletonComponentProps, { skeletonsAnimation: false, actions: _jsx(CreateEventButton, {}) })), _jsx(Typography, Object.assign({ variant: "body1" }, { children: _jsx(FormattedMessage, { id: "ui.events.noEvents.title.onlyStaff", defaultMessage: "ui.events.noEvents.title.onlyStaff" }) }))] })) }))) : (_jsxs(_Fragment, { children: [_jsx(Grid, Object.assign({ container: true, spacing: { xs: 2 }, className: classes.events }, GridContainerComponentProps, { children: _jsxs(_Fragment, { children: [events.map((event) => (_jsx(Grid, Object.assign({ item: true, xs: 12, sm: 12, md: 6, className: classes.item }, GridItemComponentProps, { children: _jsx(Event, Object.assign({ event: event, eventId: event.id }, EventComponentProps)) }), event.id))), authUserId && events.length % 2 !== 0 && (_jsx(Grid, Object.assign({ item: true, xs: 12, sm: 12, md: 6, className: classes.itemSkeleton }, GridItemComponentProps, { children: _jsx(EventSkeleton, Object.assign({}, EventSkeletonComponentProps, { skeletonsAnimation: false, actions: _jsx(CreateEventButton, Object.assign({ variant: "outlined", color: "primary", size: "small" }, { children: _jsx(FormattedMessage, { id: "ui.events.skeleton.action.add", defaultMessage: "ui.events.skeleton.action.add" }) })) })) }), 'skeleton-item'))] }) })), Boolean(next) && (_jsx(Button, Object.assign({ color: "secondary", variant: "text", onClick: handleNext, className: classes.showMore }, { children: _jsx(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 (_jsx(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: c })));
}
