"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const lab_1 = require("@mui/lab");
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 utils_1 = require("@selfcommunity/utils");
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 BaseDialog_1 = tslib_1.__importDefault(require("../../shared/BaseDialog"));
const ConfirmDialog_1 = tslib_1.__importDefault(require("../../shared/ConfirmDialog/ConfirmDialog"));
const HiddenPlaceholder_1 = tslib_1.__importDefault(require("../../shared/HiddenPlaceholder"));
const InfiniteScroll_1 = tslib_1.__importDefault(require("../../shared/InfiniteScroll"));
const Lightbox_1 = require("../../shared/Lightbox");
const widget_1 = require("../../utils/widget");
const Widget_1 = tslib_1.__importDefault(require("../Widget"));
const constants_1 = require("./constants");
const Skeleton_1 = tslib_1.__importStar(require("./Skeleton"));
const TriggerButton_1 = tslib_1.__importDefault(require("./TriggerButton"));
const messages = (0, react_intl_1.defineMessages)({
    title: {
        id: 'ui.eventMediaWidget.title',
        defaultMessage: 'ui.eventMediaWidget.title'
    }
});
const MEDIAS_TO_SHOW = 9;
const classes = {
    root: `${constants_1.PREFIX}-root`,
    header: `${constants_1.PREFIX}-header`,
    grid: `${constants_1.PREFIX}-grid`,
    media: `${constants_1.PREFIX}-media`,
    mediaLayer: `${constants_1.PREFIX}-media-layer`,
    countHiddenMediaWrapper: `${constants_1.PREFIX}-count-hidden-media-wrapper`,
    countHiddenMedia: `${constants_1.PREFIX}-count-hidden-media`,
    content: `${constants_1.PREFIX}-content`,
    actions: `${constants_1.PREFIX}-actions`,
    dialogRoot: `${constants_1.PREFIX}-dialog-root`,
    dialogInfiniteScroll: `${constants_1.PREFIX}-dialog-infinite-scroll`,
    dialogMediaWrapper: `${constants_1.PREFIX}-dialog-media-wrapper`,
    dialogButtonWrapper: `${constants_1.PREFIX}-dialog-button-wrapper`,
    dialogLoadingButton: `${constants_1.PREFIX}-dialog-loading-button`,
    endMessage: `${constants_1.PREFIX}-end-message`
};
const Root = (0, styles_1.styled)(Widget_1.default, {
    name: constants_1.PREFIX,
    slot: 'Root',
    overridesResolver: (_props, styles) => styles.root,
    shouldForwardProp: (prop) => prop !== 'showPadding'
})(() => ({}));
const DialogRoot = (0, styles_1.styled)(BaseDialog_1.default, {
    name: constants_1.PREFIX,
    slot: 'DialogRoot',
    overridesResolver: (_props, styles) => styles.dialogRoot,
    shouldForwardProp: (prop) => prop !== 'loading'
})(() => ({}));
function EventMediaWidget(inProps) {
    // PROPS
    const props = (0, system_1.useThemeProps)({
        props: inProps,
        name: constants_1.PREFIX
    });
    // CONST
    const { event, eventId, limit = Pagination_1.DEFAULT_PAGINATION_LIMIT, endpointQueryParams = {
        limit,
        offset: Pagination_1.DEFAULT_PAGINATION_OFFSET
    }, cacheStrategy = utils_1.CacheStrategies.CACHE_FIRST, dialogProps } = props, rest = tslib_1.__rest(props, ["event", "eventId", "limit", "endpointQueryParams", "cacheStrategy", "dialogProps"]);
    // HOOKS
    const { scEvent } = (0, react_core_1.useSCFetchEvent)({ id: eventId, event });
    const intl = (0, react_intl_1.useIntl)();
    const theme = (0, material_1.useTheme)();
    const isMobile = (0, material_1.useMediaQuery)(theme.breakpoints.down('md'));
    // STATE
    const [state, dispatch] = (0, react_1.useReducer)(widget_1.dataWidgetReducer, {
        isLoadingNext: false,
        next: null,
        cacheKey: react_core_1.SCCache.getWidgetStateCacheKey(react_core_1.SCCache.EVENT_MEDIA_STATE_CACHE_PREFIX_KEY, event ? event.id : eventId),
        cacheStrategy,
        visibleItems: limit
    }, widget_1.stateWidgetInitializer);
    const [medias, setMedias] = (0, react_1.useState)(state.results);
    const [mediasCount, setMediasCount] = (0, react_1.useState)(state.count);
    const [openDialog, setOpenDialog] = (0, react_1.useState)(false);
    const [openDialogConfirm, setOpenDialogConfirm] = (0, react_1.useState)(false);
    const [mediaId, setMediaId] = (0, react_1.useState)(null);
    const [preview, setPreview] = (0, react_1.useState)(-1);
    const [loading, setLoading] = (0, react_1.useState)(false);
    const [showSkeleton, setShowSkeleton] = (0, react_1.useState)(null);
    // CONTEXT
    const scUserContext = (0, react_core_1.useSCUser)();
    // CONSTS
    const hasAllow = (0, react_1.useMemo)(() => { var _a; return ((_a = scUserContext.user) === null || _a === void 0 ? void 0 : _a.id) === (scEvent === null || scEvent === void 0 ? void 0 : scEvent.managed_by.id); }, [scUserContext, scEvent]);
    const countHiddenMedia = (0, react_1.useMemo)(() => mediasCount - MEDIAS_TO_SHOW, [mediasCount]);
    const _fetchNext = (0, react_1.useCallback)((index) => {
        if (mediasCount > medias.length && index >= 6 && !state.isLoadingNext && state.next) {
            setPreview(index);
            dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.http
                .request({
                url: state.next,
                method: api_services_1.Endpoints.GetEventPhotoGallery.method
            })
                .then((res) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
                setMedias((prev) => [...prev, ...res.data.results]);
                setMediasCount(res.data.count);
            })
                .catch((error) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [state.next, state.isLoadingNext, medias, mediasCount, dispatch, setPreview]);
    const handleOpenLightbox = (0, react_1.useCallback)((index) => {
        setPreview(index);
    }, [setPreview]);
    const handleCloseLightbox = (0, react_1.useCallback)(() => {
        setPreview(-1);
    }, [setPreview]);
    const handleToggleDialogOpen = (0, react_1.useCallback)(() => {
        setOpenDialog((prev) => !prev);
    }, [setOpenDialog]);
    const handleNext = (0, react_1.useCallback)(() => {
        setShowSkeleton('dialog');
        dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
        api_services_1.http
            .request({
            url: state.next,
            method: api_services_1.Endpoints.GetEventPhotoGallery.method
        })
            .then((res) => {
            dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: res.data });
            setMedias((prev) => [...prev, ...res.data.results]);
            setMediasCount(res.data.count);
            setShowSkeleton(null);
        })
            .catch((error) => {
            dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
        });
    }, [state.next, state.isLoadingNext, state.initialized, dispatch, setMedias, setMediasCount, setShowSkeleton]);
    const handleRemoveMedia = (0, react_1.useCallback)((id) => {
        if (hasAllow) {
            setMediaId(id);
            setOpenDialogConfirm(true);
        }
    }, [setMediaId, setOpenDialogConfirm]);
    const handleConfirmAction = (0, react_1.useCallback)(() => {
        setLoading(true);
        api_services_1.http
            .request({
            url: api_services_1.Endpoints.RemoveMediasFromEventPhotoGallery.url({ id: scEvent.id }),
            method: api_services_1.Endpoints.RemoveMediasFromEventPhotoGallery.method,
            data: { medias: [mediaId] }
        })
            .then(() => {
            setMedias((prev) => prev.filter((media) => media.id !== mediaId));
            setMediasCount((prev) => prev - 1);
            setMediaId(null);
            setLoading(false);
            setOpenDialogConfirm(false);
        })
            .catch((error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
        });
    }, [scEvent, mediaId, setMedias, setLoading, setOpenDialogConfirm, dispatch, setMediasCount]);
    const handleCloseAction = (0, react_1.useCallback)(() => {
        setMediaId(null);
        setOpenDialogConfirm(false);
    }, [setMediaId, setOpenDialogConfirm]);
    const handleAddMedia = (0, react_1.useCallback)((media) => {
        setShowSkeleton('widget');
        api_services_1.http
            .request({
            url: api_services_1.Endpoints.AddMediaToEventPhotoGallery.url({ id: scEvent.id }),
            method: api_services_1.Endpoints.AddMediaToEventPhotoGallery.method,
            data: { media: media.id }
        })
            .then((res) => {
            setMedias((prev) => [res.data, ...prev]);
            setMediasCount((prev) => prev + 1);
            setShowSkeleton(null);
        })
            .catch((error) => {
            utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
        });
    }, [scEvent, setMedias, setMediasCount, setShowSkeleton]);
    // EFFECTS
    (0, react_1.useEffect)(() => {
        let _t;
        if (scUserContext.user &&
            scEvent &&
            !state.initialized &&
            Boolean((eventId !== undefined && scEvent.id === eventId) || (event && scEvent.id === event.id))) {
            _t = setTimeout(_initComponent);
            return () => {
                clearTimeout(_t);
            };
        }
    }, [scUserContext.user, scEvent, state.initialized]);
    (0, react_1.useEffect)(() => {
        if (state.initialized && scEvent && Boolean((eventId !== undefined && scEvent.id !== eventId) || (event && scEvent.id !== event.id))) {
            dispatch({ type: widget_1.actionWidgetTypes.RESET, payload: {} });
        }
    }, [state.initialized, scEvent, eventId, event]);
    /**
     * Initialize component
     * Fetch data only if the component is not initialized and it is not loading data
     */
    const _initComponent = (0, react_1.useCallback)(() => {
        if (!state.isLoadingNext) {
            dispatch({ type: widget_1.actionWidgetTypes.LOADING_NEXT });
            api_services_1.EventService.getEventPhotoGallery(scEvent.id, Object.assign({}, endpointQueryParams))
                .then((payload) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_SUCCESS, payload: Object.assign(Object.assign({}, payload), { initialized: true }) });
                setMedias(payload.results);
                setMediasCount(payload.count);
            })
                .catch((error) => {
                dispatch({ type: widget_1.actionWidgetTypes.LOAD_NEXT_FAILURE, payload: { errorLoadNext: error } });
                utils_1.Logger.error(Errors_1.SCOPE_SC_UI, error);
            });
        }
    }, [state.isLoadingNext, scEvent, eventId, dispatch, setMedias, setMediasCount]);
    (0, react_1.useEffect)(() => {
        if (isMobile && openDialog && state.next) {
            handleNext();
        }
    }, [isMobile, openDialog, state.next]);
    // RENDER
    if (!scEvent ||
        !state.initialized ||
        (scEvent && ((eventId !== undefined && scEvent.id !== eventId) || (event && scEvent.id !== event.id))) ||
        (state.isLoadingNext && !state.initialized)) {
        return (0, jsx_runtime_1.jsx)(Skeleton_1.default, {});
    }
    if (state.initialized && state.count === 0 && !hasAllow) {
        return (0, jsx_runtime_1.jsx)(HiddenPlaceholder_1.default, {});
    }
    return ((0, jsx_runtime_1.jsxs)(Root, Object.assign({ className: classes.root }, rest, { showPadding: hasAllow }, { children: [(0, jsx_runtime_1.jsx)(material_1.CardHeader, { title: (0, jsx_runtime_1.jsxs)(material_1.Stack, Object.assign({ direction: "row", justifyContent: "space-between", alignItems: "center" }, { children: [(0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ variant: "h5" }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMediaWidget.title", defaultMessage: "ui.eventMediaWidget.title" }) })), hasAllow && mediasCount > 0 && (0, jsx_runtime_1.jsx)(TriggerButton_1.default, { size: "small", onAdd: handleAddMedia })] })), className: classes.header }), (0, jsx_runtime_1.jsx)(material_1.Divider, {}), (0, jsx_runtime_1.jsxs)(material_1.CardContent, Object.assign({ className: classes.content }, { children: [(0, jsx_runtime_1.jsxs)(system_1.Box, Object.assign({ className: classes.grid }, { children: [showSkeleton === 'widget' && (0, jsx_runtime_1.jsx)(Skeleton_1.EventMediaSkeleton, {}), medias.slice(0, MEDIAS_TO_SHOW).map((media, i, array) => ((0, jsx_runtime_1.jsx)(system_1.Box, Object.assign({ onClick: () => handleOpenLightbox(i), sx: {
                                    background: `url(${media.image}) no-repeat center`
                                }, className: classes.media }, { children: medias.length > array.length && i === array.length - 1 && ((0, jsx_runtime_1.jsxs)(react_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(system_1.Box, { className: classes.mediaLayer }), (0, jsx_runtime_1.jsx)(system_1.Box, Object.assign({ className: classes.countHiddenMediaWrapper }, { children: (0, jsx_runtime_1.jsxs)(material_1.Typography, Object.assign({ className: classes.countHiddenMedia }, { children: ["+", countHiddenMedia] })) }))] })) }), media.id))), hasAllow && mediasCount === 0 && ((0, jsx_runtime_1.jsx)(material_1.Tooltip, Object.assign({ title: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMediaWidget.add", defaultMessage: "ui.eventMediaWidget.add" }) }, { children: (0, jsx_runtime_1.jsx)(TriggerButton_1.default, { size: "large", onAdd: handleAddMedia, isSquare: true }) })))] })), preview !== -1 && (0, jsx_runtime_1.jsx)(Lightbox_1.Lightbox, { onClose: handleCloseLightbox, index: preview, medias: medias, onIndexChange: _fetchNext })] })), hasAllow && mediasCount > 0 && ((0, jsx_runtime_1.jsx)(material_1.CardActions, Object.assign({ className: classes.actions }, { children: (0, jsx_runtime_1.jsx)(material_1.Button, Object.assign({ onClick: handleToggleDialogOpen }, { 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.eventMediaWidget.showAll", defaultMessage: "ui.eventMediaWidget.showAll" }) })) })) }))), openDialog && ((0, jsx_runtime_1.jsx)(DialogRoot, Object.assign({ className: classes.dialogRoot, title: intl.formatMessage(messages.title, { user: scEvent.managed_by.username }), onClose: handleToggleDialogOpen, open: openDialog }, dialogProps, { children: (0, jsx_runtime_1.jsx)(InfiniteScroll_1.default, Object.assign({ dataLength: medias.length, height: isMobile ? '100%' : '515px', next: handleNext, hasMoreNext: Boolean(state.next), className: classes.dialogInfiniteScroll, endMessage: (0, jsx_runtime_1.jsx)(material_1.Typography, Object.assign({ className: classes.endMessage }, { children: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMediaWidget.noMoreResults", defaultMessage: "ui.eventMediaWidget.noMoreResults" }) })) }, { children: (0, jsx_runtime_1.jsxs)(system_1.Box, Object.assign({ className: classes.grid }, { children: [medias.map((media) => ((0, jsx_runtime_1.jsx)(system_1.Box, Object.assign({ sx: {
                                    background: `url(${media.image}) no-repeat center`
                                }, className: classes.dialogMediaWrapper }, { children: (0, jsx_runtime_1.jsx)(material_1.Stack, Object.assign({ className: classes.dialogButtonWrapper }, { children: (0, jsx_runtime_1.jsx)(lab_1.LoadingButton, Object.assign({ className: classes.dialogLoadingButton, loading: mediaId === media.id, size: "large", onClick: () => handleRemoveMedia(media.id), sx: {
                                            color: (theme) => (mediaId === media.id ? 'transparent' : theme.palette.common.white)
                                        } }, { children: (0, jsx_runtime_1.jsx)(material_1.Icon, Object.assign({ fontSize: "inherit" }, { children: "delete" })) })) })) }), media.id))), showSkeleton === 'dialog' && Array.from(Array(countHiddenMedia)).map((_, i) => (0, jsx_runtime_1.jsx)(Skeleton_1.EventMediaSkeleton, {}, i))] })) })) }))), openDialogConfirm && ((0, jsx_runtime_1.jsx)(ConfirmDialog_1.default, { open: openDialogConfirm, title: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMediaWidget.dialog.title", defaultMessage: "ui.eventMediaWidget.dialog.title" }), content: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMediaWidget.dialog.msg", defaultMessage: "ui.eventMediaWidget.dialog.msg" }), btnConfirm: (0, jsx_runtime_1.jsx)(react_intl_1.FormattedMessage, { id: "ui.eventMediaWidget.dialog.confirm", defaultMessage: "ui.eventMediaWidget.dialog.confirm" }), isUpdating: loading, onConfirm: handleConfirmAction, onClose: handleCloseAction }))] })));
}
exports.default = EventMediaWidget;
