import * as React from 'react';
import { useSelector } from 'react-redux';
import { Icon } from '../../components/icons';
import Panel from '../../components/Panel';
import SimpleButton from '../../components/SimpleButton';
import * as CommentsRedux from '../../Redux/ActionsReducers/CommentsRedux';
import { CommentsAndNotesSelector } from '../../Redux/ActionsReducers/InternalRedux';
import { useAdaptable } from '../AdaptableContext';
import AdaptableInput from '../Components/AdaptableInput';
import FormatHelper from '../../Utilities/Helpers/FormatHelper';
import { Box, Flex } from '../../components/Flex';
// Edit Mode
// [author] [edit, delete]
// [text-editor] * this is different
// [show-all-comments-button]
// View Mode
// [author] [edit, delete]
// [text]
// [show-all-comments-button]
export const CommentsEditor = (props) => {
    const { api } = useAdaptable();
    const showCloseButton = api.optionsApi.getCommentOptions()?.showPopupCloseButton ?? true;
    const cellAddress = useSelector((state) => CommentsAndNotesSelector(state.Internal));
    const userId = React.useMemo(() => {
        return api.optionsApi.getUserName();
    }, []);
    const commentThread = useSelector((state) => CommentsRedux.GetCellCommentSelector(state.Comment, cellAddress));
    const isReadOnlyModule = api.entitlementApi.getEntitlementAccessLevelForModule('Comment') === 'ReadOnly';
    const [activeEditingComment, setActiveEditingComment] = React.useState(() => {
        /**
         * When opening the popup and there is only one comment, we want to open it in edit mode.
         * This happens usualy when a new comment is added via cell menu.
         */
        // if (cellComments?.Comments?.length === 1 && cellComments?.Comments[0].Value === '') {
        //   return cellComments?.Comments[0].Uuid;
        // }
        return null;
    });
    const [newCommentText, setNewCommentText] = React.useState('');
    const commentsWrapperRef = React.useRef(null);
    const comments = commentThread?.Comments;
    const scrollToBottom = () => {
        commentsWrapperRef?.current?.scrollTo(0, commentsWrapperRef?.current?.scrollHeight);
    };
    React.useEffect(() => {
        scrollToBottom();
    }, []);
    if (!commentThread) {
        return null;
    }
    const formatDate = (date, format) => {
        return FormatHelper.DateFormatter(date, { Pattern: format });
    };
    return (React.createElement(Panel, { color: "var(--ab-color-text-on-primary)", onClick: () => props.enableEditMode(), className: "ab-CommentPopup twa:min-w-[250px]", onKeyDown: (event) => {
            if (event.key === 'Escape') {
                api.commentApi.hideCommentsPopup();
            }
        } },
        showCloseButton && (React.createElement(Flex, null,
            React.createElement(Box, { className: "twa:flex-1" }),
            React.createElement(SimpleButton, { onClick: (event) => {
                    event.stopPropagation();
                    api.commentApi.hideCommentsPopup();
                }, variant: "text", icon: "close" }))),
        React.createElement(Flex, { className: "twa:overflow-auto twa:max-h-[300px]", flexDirection: "column", ref: commentsWrapperRef }, comments &&
            comments.length > 0 &&
            comments.map((comment, index) => {
                if (!comment) {
                    return null;
                }
                const isOwnComment = comment?.Author?.UserName
                    ? comment?.Author?.UserName === userId
                    : true; // no owner means it's the current user
                return (React.createElement(Box, { key: comment.Uuid ?? index, className: "ab-Comment twa:p-2" },
                    React.createElement(Flex, { alignItems: "center", className: "twa:mb-2" },
                        React.createElement(Box, null,
                            React.createElement(Box, { "data-name": "comment-username", className: "twa:text-3 twa:font-bold" }, comment?.Author?.UserName),
                            comment.Timestamp && (React.createElement(Box, { "data-name": "comment-timestamp", className: "twa:text-2" }, formatDate(comment.Timestamp, api.commentApi.internalApi.getCommentsDateFormat())))),
                        React.createElement(Box, { className: "twa:flex-1" }),
                        React.createElement(SimpleButton, { variant: "text", icon: "edit", disabled: !isOwnComment || isReadOnlyModule, onClick: () => setActiveEditingComment(comment.Uuid) }),
                        React.createElement(SimpleButton, { variant: "text", icon: "delete", disabled: !isOwnComment || isReadOnlyModule, onClick: () => {
                                api.commentApi.deleteComment(comment, cellAddress);
                                requestAnimationFrame(() => {
                                    props.onRefreshContent();
                                });
                            } })),
                    React.createElement(Box, { onClick: () => setActiveEditingComment(comment.Uuid) }, comment.Uuid === activeEditingComment ? (React.createElement(AdaptableInput, { autoFocus: true, className: "twa:w-full", defaultValue: comment.Value, disabled: isReadOnlyModule, onBlur: () => {
                            if (comment.Uuid === activeEditingComment) {
                                setActiveEditingComment(null);
                            }
                        }, onChange: (event) => {
                            api.commentApi.editComment({
                                ...comment,
                                Value: event.target.value,
                            }, cellAddress);
                        } })) : (React.createElement(Box, { "data-name": "comment-text" }, comment.Value)))));
            })),
        React.createElement(AdaptableInput, { autoFocus: !comments || comments.length === 0, value: newCommentText, disabled: isReadOnlyModule, onChange: (event) => {
                setNewCommentText(event.target.value);
            }, onKeyDown: (event) => {
                if (event.key === 'Enter') {
                    api.commentApi.addComment(newCommentText, cellAddress);
                    setNewCommentText('');
                    requestAnimationFrame(() => {
                        props.onRefreshContent();
                        scrollToBottom();
                    });
                }
            }, className: "twa:w-full twa:my-2", placeholder: "Write new Comment" }),
        React.createElement(SimpleButton, { className: "twa:w-full", variant: "raised", onClick: () => {
                api.settingsPanelApi.openSettingsPanel('Comment');
                api.internalApi.getAnnotationsService().hidePopup();
            } },
            React.createElement(Box, { className: "twa:mr-2" },
                React.createElement(Icon, { name: "folder" })),
            ' ',
            "Open all Comments")));
};
