import { __rest } from "tslib";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useMemo } from 'react';
import { styled } from '@mui/material/styles';
import { FormattedMessage } from 'react-intl';
import CommentObject, { CommentObjectSkeleton } from '../CommentObject';
import Typography from '@mui/material/Typography';
import { Box, Button, Stack } from '@mui/material';
import classNames from 'classnames';
import CustomAdv from '../CustomAdv';
import { useThemeProps } from '@mui/system';
import CommentsObjectSkeleton from './Skeleton';
import { InView } from 'react-intersection-observer';
import { getContributionRouteName, getRouteData } from '../../utils/contribution';
import { SCContributionType, SCCustomAdvPosition } from '@selfcommunity/types';
import { appendURLSearchParams, CacheStrategies } from '@selfcommunity/utils';
import { DEFAULT_PAGINATION_QUERY_PARAM_NAME } from '../../constants/Pagination';
import { Link, SCPreferences, useSCFetchFeedObject, useSCPreferences, useSCRouting, useSCUser } from '@selfcommunity/react-core';
import { PREFIX } from './constants';
const classes = {
    root: `${PREFIX}-root`,
    loadNextCommentsButton: `${PREFIX}-load-more-comments-button`,
    loadPreviousCommentsButton: `${PREFIX}-load-previous-comments-button`,
    paginationLink: `${PREFIX}-pagination-link`,
    pagination: `${PREFIX}-pagination`,
    commentsCounter: `${PREFIX}-comments-counter`,
    commentNotFound: `${PREFIX}-comment-not-found`,
    noOtherComments: `${PREFIX}-no-other-comment`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'Root'
})(() => ({}));
const PREFERENCES = [SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED, SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED];
/**
 * > API documentation for the Community-JS Comments Object component. Learn about the available props and the CSS API.

 #### Import

 ```jsx
 import {CommentsObject} from '@selfcommunity/react-ui';
 ```

 #### Component Name

 The name `SCCommentsObject` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCCommentsObject-root|Styles applied to the root element.|
 |pagination|.SCCommentsObject-pagination|Styles applied to the pagination controls.|
 |paginationLink|.SCCommentsObject-pagination-link|Styles applied to the pagination link.|
 |loadNextCommentsButton|.SCCommentsObject-load-next-comments-button|Styles applied to the load next comments button.|
 |loadPreviousCommentsButton|.SCCommentsObject-load-previous-comments-button|Styles applied to the load previous comments button.|
 |commentsCounter|.SCCommentsObject-comments-counter|Styles applied to the comments counter element.|

 * @param inProps
 */
export default function CommentsObject(inProps) {
    const props = useThemeProps({
        props: inProps,
        name: PREFIX
    });
    // PROPS
    const { id = `comments_object_${props.feedObjectId ? props.feedObjectId : props.feedObject ? props.feedObject.id : ''}`, className, feedObjectId, feedObject, feedObjectType = SCContributionType.POST, CommentComponent = CommentObject, CommentComponentProps = { variant: 'outlined' }, CommentObjectSkeletonProps = { elevation: 0, WidgetProps: { variant: 'outlined' } }, CommentsObjectSkeletonProps = {}, next, isLoadingNext, handleNext, previous, isLoadingPrevious, handlePrevious, totalLoadedComments, totalComments, page, previousPage, nextPage, comments = [], startComments = [], endComments = [], infiniteScrolling = false, hideAdvertising = false, disablePaginationLinks = false, hidePaginationLinks = true, inPlaceLoadMoreContents = true, paginationLinksPageQueryParam = DEFAULT_PAGINATION_QUERY_PARAM_NAME, PaginationLinkProps = {}, cacheStrategy = CacheStrategies.NETWORK_ONLY } = props, rest = __rest(props, ["id", "className", "feedObjectId", "feedObject", "feedObjectType", "CommentComponent", "CommentComponentProps", "CommentObjectSkeletonProps", "CommentsObjectSkeletonProps", "next", "isLoadingNext", "handleNext", "previous", "isLoadingPrevious", "handlePrevious", "totalLoadedComments", "totalComments", "page", "previousPage", "nextPage", "comments", "startComments", "endComments", "infiniteScrolling", "hideAdvertising", "disablePaginationLinks", "hidePaginationLinks", "inPlaceLoadMoreContents", "paginationLinksPageQueryParam", "PaginationLinkProps", "cacheStrategy"]);
    // CONTEXT
    const scUserContext = useSCUser();
    const scPreferences = useSCPreferences();
    const scRoutingContext = useSCRouting();
    const { obj } = useSCFetchFeedObject({ id: feedObjectId, feedObject, feedObjectType, cacheStrategy });
    const commentsIds = comments.map((c) => c.id);
    const advPosition = Math.floor(Math.random() * (Math.min(comments.length, 5) - 1 + 1) + 1);
    /**
     * Compute preferences
     */
    const preferences = useMemo(() => {
        const _preferences = {};
        PREFERENCES.map((p) => (_preferences[p] = p in scPreferences.preferences ? scPreferences.preferences[p].value : null));
        return _preferences;
    }, [scPreferences.preferences]);
    /**
     * Render advertising above FeedObject Detail
     */
    const renderAdvertising = useMemo(() => () => {
        if (obj &&
            !hideAdvertising &&
            preferences[SCPreferences.ADVERTISING_CUSTOM_ADV_ENABLED] &&
            ((preferences[SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED] && scUserContext.user === null) ||
                !preferences[SCPreferences.ADVERTISING_CUSTOM_ADV_ONLY_FOR_ANONYMOUS_USERS_ENABLED])) {
            return (_jsx(CustomAdv, Object.assign({ position: SCCustomAdvPosition.POSITION_IN_COMMENTS }, (obj.categories.length && { categoriesId: obj.categories.map((c) => c.id) }))));
        }
        return null;
    }, [JSON.stringify(obj)]);
    /**
     * Handle open reply box
     * @param comment
     */
    function openReplyBox(comment) {
        setTimeout(() => {
            const element = document.getElementById(`reply-${comment.id}`);
            if (element) {
                element.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' });
            }
        }, 200);
    }
    /**
     * handle on scroll end
     * @param inView
     * @param entry
     */
    function handleScrollEnd(inView, entry) {
        if (infiniteScrolling && inView && !isLoadingNext) {
            handleNext && handleNext();
        }
    }
    /**
     * Check if show Comments counter
     */
    function showCommentsCounter() {
        return Boolean(totalComments && totalLoadedComments);
    }
    /**
     * Render button load previous comments
     */
    function renderLoadPreviousComments() {
        return (_jsxs(Box, Object.assign({ className: classes.pagination }, { children: [isLoadingPrevious && _jsx(CommentObjectSkeleton, Object.assign({}, CommentObjectSkeletonProps, { count: 1 })), !isLoadingPrevious && (_jsxs(_Fragment, { children: [_jsx(Button, Object.assign({ variant: "text" }, (inPlaceLoadMoreContents
                            ? { onClick: handlePrevious }
                            : {
                                component: Link,
                                to: `${scRoutingContext.url(getContributionRouteName(feedObject), getRouteData(feedObject))}`
                            }), { disabled: isLoadingPrevious, color: "inherit", classes: { root: classes.loadPreviousCommentsButton } }, { children: _jsx(FormattedMessage, { id: "ui.commentsObject.loadPreviousComments", defaultMessage: "ui.commentsObject.loadPreviousComments" }) })), !disablePaginationLinks && previousPage && previous && (_jsx(Link, Object.assign({ to: `${appendURLSearchParams(scRoutingContext.url(getContributionRouteName(feedObject), getRouteData(feedObject)), [
                                { [paginationLinksPageQueryParam]: previousPage }
                            ])}`, className: classNames({ [classes.paginationLink]: hidePaginationLinks }) }, PaginationLinkProps, { children: _jsx(FormattedMessage, { id: "ui.commentsObject.previousComments", defaultMessage: "ui.commentsObject.previousComments" }) })))] }))] })));
    }
    /**
     * Footer with n comments of, only for load more pagination mode
     */
    function renderLoadNextComments() {
        return (_jsx(Box, Object.assign({ className: classes.pagination }, { children: isLoadingNext ? (_jsx(CommentObjectSkeleton, Object.assign({}, CommentObjectSkeletonProps, { count: 1 }))) : (_jsxs(_Fragment, { children: [_jsx(InView, Object.assign({ as: "div", onChange: handleScrollEnd, threshold: 0.5 }, { children: _jsxs(Stack, Object.assign({ direction: "row", justifyContent: "space-between", alignItems: "center", spacing: 2 }, { children: [_jsx(Button, Object.assign({ variant: "text" }, (inPlaceLoadMoreContents
                                    ? { onClick: handleNext }
                                    : {
                                        component: Link,
                                        to: nextPage && next
                                            ? `${appendURLSearchParams(scRoutingContext.url(getContributionRouteName(feedObject), getRouteData(feedObject)), [
                                                { [paginationLinksPageQueryParam]: nextPage }
                                            ])}`
                                            : `${scRoutingContext.url(getContributionRouteName(feedObject), getRouteData(feedObject))}`
                                    }), { disabled: isLoadingNext, color: "inherit", classes: { root: classes.loadNextCommentsButton } }, { children: _jsx(FormattedMessage, { id: "ui.commentsObject.loadMoreComments", defaultMessage: "ui.commentsObject.loadMoreComments" }) })), showCommentsCounter() && (_jsx(Typography, Object.assign({ variant: "body1", classes: { root: classes.commentsCounter } }, { children: _jsx(FormattedMessage, { id: "ui.commentsObject.numberOfComments", defaultMessage: "ui.commentsObject.numberOfComments", values: { loaded: totalLoadedComments, total: totalComments } }) })))] })) })), !disablePaginationLinks && nextPage && next && (_jsx(Link, Object.assign({ to: `${appendURLSearchParams(scRoutingContext.url(getContributionRouteName(feedObject), getRouteData(feedObject)), [
                            { [paginationLinksPageQueryParam]: nextPage }
                        ])}`, className: classNames({ [classes.paginationLink]: hidePaginationLinks }) }, PaginationLinkProps, { children: _jsx(FormattedMessage, { id: "ui.commentsObject.nextComments", defaultMessage: "ui.commentsObject.nextComments" }) })))] })) })));
    }
    /**
     * Remove duplicate comments (from header or footer)
     * @param comments
     */
    function getFilteredComments(comments) {
        return comments.filter((c) => !commentsIds.includes(c.id));
    }
    /**
     * Render comments and load others with load more button
     */
    function renderComments(comments) {
        return (_jsx(_Fragment, { children: comments.map((comment, index) => (_jsxs(React.Fragment, { children: [_jsx(CommentComponent, Object.assign({ commentObject: comment, onOpenReply: openReplyBox, feedObject: obj }, CommentComponentProps, { CommentObjectSkeletonProps: CommentObjectSkeletonProps }), comment.id), advPosition === index && renderAdvertising()] }, index))) }));
    }
    /**
     * Render comments
     */
    let commentsRendered = _jsx(_Fragment, {});
    if (!obj || ((isLoadingPrevious || isLoadingNext) && !comments.length)) {
        /**
         * Until the contribution has not been founded and there are
         * no comments during loading render skeletons
         */
        commentsRendered = _jsx(CommentsObjectSkeleton, Object.assign({ CommentObjectSkeletonProps: CommentObjectSkeletonProps }, CommentsObjectSkeletonProps));
    }
    else {
        /**
         * Two modes available:
         *  - infinite scroll
         *  - load pagination with load next comment button
         *  !IMPORTANT:
         *  the component will switch to 'load more pagination' mode automatically
         *  in case it needs to display a single comment or newComments
         */
        commentsRendered = (_jsxs(_Fragment, { children: [previous && renderLoadPreviousComments(), renderComments(comments), next && renderLoadNextComments()] }));
    }
    /**
     * Renders root object
     */
    return (_jsxs(Root, Object.assign({ id: id, className: classNames(classes.root, className) }, rest, { children: [renderComments(getFilteredComments(startComments)), commentsRendered, renderComments(getFilteredComments(endComments))] })));
}
