"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const material_1 = require("@mui/material");
const system_1 = require("@mui/system");
const api_services_1 = require("@selfcommunity/api-services");
const react_core_1 = require("@selfcommunity/react-core");
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 react_2 = require("swiper/react");
const Errors_1 = require("../../constants/Errors");
const Pagination_1 = require("../../constants/Pagination");
const HiddenPlaceholder_1 = tslib_1.__importDefault(require("../../shared/HiddenPlaceholder"));
const event_1 = require("../../types/event");
const Event_1 = tslib_1.__importDefault(require("../Event"));
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const Arrow_1 = tslib_1.__importDefault(require("./Arrow"));
const constants_1 = require("./constants");
const Skeleton_1 = tslib_1.__importDefault(require("./Skeleton"));
const pubsub_js_1 = tslib_1.__importDefault(require("pubsub-js"));
const PubSub_1 = require("../../constants/PubSub");
const classes = {
    root: `${constants_1.PREFIX}-root`,
    content: `${constants_1.PREFIX}-content`,
    title: `${constants_1.PREFIX}-title`,
    swiper: `${constants_1.PREFIX}-swiper`,
    swiperSlide: `${constants_1.PREFIX}-swiper-slide`,
    swiperArrow: `${constants_1.PREFIX}-swiper-arrow`,
    swiperPrevArrow: `${constants_1.PREFIX}-swiper-prev-arrow`,
    swiperNextArrow: `${constants_1.PREFIX}-swiper-next-arrow`,
    event: `${constants_1.PREFIX}-event`,
    actions: `${constants_1.PREFIX}-actions`,
    actionButton: `${constants_1.PREFIX}-action-button`
};
const Root = (0, system_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root
})(() => ({}));
function SuggestedEventsWidget(inProps) {
    // PROPS
    const props = (0, material_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    const { endpointQueryParams = { limit: 3, offset: Pagination_1.DEFAULT_PAGINATION_OFFSET } } = props, rest = tslib_1.__rest(props, ["endpointQueryParams"]);
    // STATE
    const [count, setCount] = (0, react_1.useState)(null);
    const [next, setNext] = (0, react_1.useState)(null);
    const [events, setEvents] = (0, react_1.useState)(null);
    const [loading, setLoading] = (0, react_1.useState)(true);
    const [showSkeleton, setShowSkeleton] = (0, react_1.useState)(false);
    const [currentItem, setCurrentItem] = (0, react_1.useState)(0);
    const [hideMarginLeft, setHideMarginLeft] = (0, react_1.useState)(false);
    const [hideMarginRight, setHideMarginRight] = (0, react_1.useState)(true);
    // CONTEXT
    const scRoutingContext = (0, react_core_1.useSCRouting)();
    //HOOKS
    const theme = (0, material_1.useTheme)();
    // REFS
    const updatesSubscription = (0, react_1.useRef)(null);
    (0, react_1.useEffect)(() => {
        api_services_1.SuggestionService.getEventSuggestion(Object.assign({}, endpointQueryParams))
            .then((payload) => {
            setCount(payload.count);
            setNext(payload.next);
            setEvents(payload.results);
            setLoading(false);
        })
            .catch((error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
        });
    }, []);
    const handleReachBeginning = (0, react_1.useCallback)(() => {
        setHideMarginLeft(false);
    }, []);
    const handleReachEnd = (0, react_1.useCallback)(() => {
        if (count > events.length && next) {
            setShowSkeleton(true);
            api_services_1.http
                .request({
                url: next,
                method: api_services_1.Endpoints.GetEventSuggestedUsers.method
            })
                .then((res) => {
                setCount(res.data.count);
                setNext(res.data.next);
                setEvents((prevEvents) => [...prevEvents, ...res.data.results]);
                setShowSkeleton(false);
            })
                .catch((error) => {
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
        else {
            setHideMarginRight(false);
        }
    }, [count, events, next]);
    const handleChange = (0, react_1.useCallback)((swiper) => {
        setCurrentItem(swiper.snapIndex);
        if (swiper.snapIndex > 0 && swiper.snapIndex < count) {
            if (!hideMarginLeft) {
                setHideMarginLeft(true);
            }
            if (!hideMarginRight) {
                setHideMarginRight(true);
            }
        }
    }, [count, hideMarginLeft, hideMarginRight]);
    /**
     * 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]);
    // RENDER
    if (!events && loading) {
        return (0, jsx_runtime_1.jsx)(Skeleton_1.default, {});
    }
    if (!events || count === 0) {
        return (0, jsx_runtime_1.jsx)(HiddenPlaceholder_1.default, {});
    }
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: classes.root }, rest, { children: [(0, jsx_runtime_1.jsxs)(material_1.CardContent, Object.assign({ className: classes.content }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h5", className: classes.title }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.suggestedEventsWidget.title", defaultMessage: "ui.suggestedEventsWidget.title" }) })), (0, jsx_runtime_1.jsxs)(react_2.Swiper, Object.assign({ spaceBetween: 8, slidesPerView: "auto", grabCursor: true, onReachBeginning: handleReachBeginning, onReachEnd: handleReachEnd, onSlideChange: handleChange, className: classes.swiper, style: {
                            marginLeft: hideMarginLeft ? `-${theme.spacing(2)}` : 0,
                            marginRight: hideMarginRight ? `-${theme.spacing(2)}` : 0
                        } }, { children: [(showSkeleton ? [...events, undefined] : events).map((event, i) => ((0, jsx_runtime_1.jsx)(react_2.SwiperSlide, Object.assign({ className: classes.swiperSlide }, { children: (0, jsx_runtime_1.jsx)(Event_1.default, { event: event, template: event_1.SCEventTemplateType.PREVIEW, actions: (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {}), variant: "outlined", className: classes.event }) }), i))), (0, jsx_runtime_1.jsx)(Arrow_1.default, { className: (0, classnames_1.default)(classes.swiperArrow, classes.swiperPrevArrow), type: "prev", currentItem: currentItem, setCurrentItem: setCurrentItem }), (0, jsx_runtime_1.jsx)(Arrow_1.default, { className: (0, classnames_1.default)(classes.swiperArrow, classes.swiperNextArrow), type: "next", currentItem: currentItem, setCurrentItem: setCurrentItem })] }))] })), (0, jsx_runtime_1.jsx)(material_1.CardActions, Object.assign({ className: classes.actions }, { children: (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ component: react_core_1.Link, to: scRoutingContext.url(react_core_1.SCRoutes.EVENTS_SUGGESTED_ROUTE_NAME, {}), className: classes.actionButton }, { children: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "caption" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.suggestedEventsWidget.showAll", defaultMessage: "ui.suggestedEventsWidget.showAll" }) })) })) }))] })));
}
exports.default = SuggestedEventsWidget;
