import React__default, { useState, useEffect, useRef, useLayoutEffect, useMemo } from 'react';
import { f as format } from '../../index-0e63045e.js';
import SuggestedMentionList from './SuggestedMentionList.js';
import useSendbirdStateContext from '../../useSendbirdStateContext.js';
import { u as useChannelContext, a as isDisabledBecauseFrozen, b as isDisabledBecauseMuted } from '../../ChannelProvider-205bb2b4.js';
import { h as getClassName } from '../../index-46da725e.js';
import { M as MAX_USER_MENTION_COUNT, a as MAX_USER_SUGGESTION_COUNT } from '../../const-4bc8cbc7.js';
import DateSeparator from '../../ui/DateSeparator.js';
import { L as Label, a as LabelTypography, b as LabelColors } from '../../index-208f60f9.js';
import MessageInput from '../../ui/MessageInput.js';
import MessageContent from '../../ui/MessageContent.js';
import FileViewer from './FileViewer.js';
import RemoveMessage from './RemoveMessageModal.js';
import { M as MessageInputKeys } from '../../const-c64639fc.js';
import { u as useLocalization } from '../../LocalizationContext-bcaf447a.js';
import { a as useHandleOnScrollCallback } from '../../index-93228741.js';
import { u as useDirtyGetMentions } from '../../useDirtyGetMentions-8a3ab1ab.js';
import '../../index-26c66412.js';
import '../../ui/Icon.js';
import 'prop-types';
import '../../ui/Avatar.js';
import '../../ui/ImageRenderer.js';
import '../../uuid-9e3aeec6.js';
import '../../ThreadProvider-7a96557d.js';
import '../../utils/message/getOutgoingMessageState.js';
import '../../UserProfileContext-96f68187.js';
import '../../_rollupPluginBabelHelpers-52628376.js';
import '../../Thread/context/types.js';
import '@sendbird/chat';
import '../../topics-50ed8c29.js';
import '@sendbird/chat/groupChannel';
import '@sendbird/chat/message';
import '../../consts-37c3d0a0.js';
import '../../withSendbird.js';
import '../../compareIds-c483b4db.js';
import '../../resolvedReplyType-bfdfe6bd.js';
import '../../color-5dee2e2d.js';
import '../../stringSet-7f300d56.js';
import '../../ui/IconButton.js';
import '../../ui/Button.js';
import 'dompurify';
import '../../consts-acdc6c08.js';
import '../../consts-c99872c0.js';
import '../../consts-cf7328d6.js';
import '../../tokenize-aa91b5a4.js';
import '../../index.module-6fe8c3f8.js';
import '../../ui/UserProfile.js';
import '../../sendbirdSelectors.js';
import '../../utils-4ce9435a.js';
import '../../index-4e834e8c.js';
import '../../ui/Loader.js';
import '../../index-fb9203f4.js';
import '../../index-1c8252a9.js';
import '../../ui/MessageItemMenu.js';
import '../../ui/ContextMenu.js';
import 'react-dom';
import '../../ui/SortByRow.js';
import '../../types-061bedf1.js';
import '../../ui/MessageItemReactionMenu.js';
import '../../ui/ReactionButton.js';
import '../../useLongPress-8b46567a.js';
import '../../MediaQueryContext-0d6b7936.js';
import '../../ui/EmojiReactions.js';
import '../../ui/ReactionBadge.js';
import '../../ui/BottomSheet.js';
import '../../index-5ca598bf.js';
import '../../ui/UserListItem.js';
import '../../ui/MutedAvatarOverlay.js';
import '../../ui/Checkbox.js';
import '../../ui/Tooltip.js';
import '../../ui/TooltipWrapper.js';
import '../../Message/context.js';
import '../../ui/AdminMessage.js';
import '../../ui/TextMessageItemBody.js';
import '../../index-78f0d986.js';
import '../../ui/MentionLabel.js';
import '../../ui/LinkLabel.js';
import '../../ui/FileMessageItemBody.js';
import '../../ui/TextButton.js';
import '../../ui/ThumbnailMessageItemBody.js';
import '../../ui/OGMessageItemBody.js';
import '../../ui/UnknownMessageItemBody.js';
import '../../ui/QuoteMessage.js';
import '../../index-c216a28a.js';
import '../../ui/ThreadReplies.js';
import '../../ui/VoiceMessageItemBody.js';
import '../../ui/ProgressBar.js';
import '../../VoicePlayer/useVoicePlayer.js';
import '../../index-dea18b86.js';
import '../../VoiceRecorder/context.js';
import '../../ui/Modal.js';
import '../../ui/PlaybackTime.js';

const useDidMountEffect = (func, deps) => {
  const [didMount, setDidmount] = useState(false);
  useEffect(() => {
    if (didMount) {
      func();
    } else {
      setDidmount(true);
    }
  }, deps);
};

// todo: Refactor this component, is too complex now
const Message = _ref => {
  var _message$reactions, _message$isUserMessag;
  let {
    message,
    hasSeparator,
    chainTop,
    chainBottom,
    handleScroll,
    handleMessageListHeightChange,
    renderCustomSeparator,
    renderEditInput,
    renderMessage,
    renderMessageContent
  } = _ref;
  const {
    dateLocale
  } = useLocalization();
  const globalStore = useSendbirdStateContext();
  const {
    userId,
    isOnline,
    isMentionEnabled,
    userMention,
    logger
  } = globalStore.config;
  const maxUserMentionCount = (userMention === null || userMention === void 0 ? void 0 : userMention.maxMentionCount) || MAX_USER_MENTION_COUNT;
  const maxUserSuggestionCount = (userMention === null || userMention === void 0 ? void 0 : userMention.maxSuggestionCount) || MAX_USER_SUGGESTION_COUNT;
  const {
    initialized,
    currentGroupChannel,
    highLightedMessageId,
    setHighLightedMessageId,
    animatedMessageId,
    setAnimatedMessageId,
    updateMessage,
    scrollToMessage,
    replyType,
    threadReplySelectType,
    isReactionEnabled,
    toggleReaction,
    emojiContainer,
    nicknamesMap,
    setQuoteMessage,
    resendMessage,
    renderUserMentionItem,
    onReplyInThread,
    onQuoteMessageClick,
    onMessageAnimated,
    onMessageHighlighted,
    onScrollCallback
  } = useChannelContext();
  const [showEdit, setShowEdit] = useState(false);
  const [showRemove, setShowRemove] = useState(false);
  const [showFileViewer, setShowFileViewer] = useState(false);
  const [isAnimated, setIsAnimated] = useState(false);
  const [isHighlighted, setIsHighlighted] = useState(false);
  const [mentionNickname, setMentionNickname] = useState('');
  const [mentionedUsers, setMentionedUsers] = useState([]);
  const [mentionedUserIds, setMentionedUserIds] = useState([]);
  const [messageInputEvent, setMessageInputEvent] = useState(null);
  const [selectedUser, setSelectedUser] = useState(null);
  const [mentionSuggestedUsers, setMentionSuggestedUsers] = useState([]);
  const editMessageInputRef = useRef(null);
  const messageScrollRef = useRef(null);
  const displaySuggestedMentionList = isOnline && isMentionEnabled && mentionNickname.length > 0 && !isDisabledBecauseFrozen(currentGroupChannel) && !isDisabledBecauseMuted(currentGroupChannel);
  const disabled = !initialized || isDisabledBecauseFrozen(currentGroupChannel) || isDisabledBecauseMuted(currentGroupChannel) || !isOnline;
  const handleOnScroll = useHandleOnScrollCallback({
    hasMore: false,
    onScroll: onScrollCallback,
    scrollRef: messageScrollRef
  });
  const mentionNodes = useDirtyGetMentions({
    ref: editMessageInputRef
  }, {
    logger
  });
  const ableMention = (mentionNodes === null || mentionNodes === void 0 ? void 0 : mentionNodes.length) < maxUserMentionCount;
  useEffect(() => {
    setMentionedUsers(mentionedUsers.filter(_ref2 => {
      let {
        userId
      } = _ref2;
      const i = mentionedUserIds.indexOf(userId);
      if (i < 0) {
        return false;
      } else {
        mentionedUserIds.splice(i, 1);
        return true;
      }
    }));
  }, [mentionedUserIds]);

  // Move the messsage list scroll when the last message's height is changed by reactions
  useDidMountEffect(() => {
    var _currentGroupChannel$;
    if ((currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$ = currentGroupChannel.lastMessage) === null || _currentGroupChannel$ === void 0 ? void 0 : _currentGroupChannel$.messageId) === (message === null || message === void 0 ? void 0 : message.messageId)) {
      handleScroll === null || handleScroll === void 0 ? void 0 : handleScroll();
    }
  }, [showEdit, message === null || message === void 0 ? void 0 : (_message$reactions = message.reactions) === null || _message$reactions === void 0 ? void 0 : _message$reactions.length]);
  useLayoutEffect(() => {
    handleMessageListHeightChange === null || handleMessageListHeightChange === void 0 ? void 0 : handleMessageListHeightChange();
  }, []);
  useLayoutEffect(() => {
    let animationTimeout = null;
    let messageHighlightedTimeout = null;
    if (highLightedMessageId === message.messageId && messageScrollRef !== null && messageScrollRef !== void 0 && messageScrollRef.current) {
      handleOnScroll();
      setIsAnimated(false);
      animationTimeout = setTimeout(() => {
        setIsHighlighted(true);
      }, 500);
      messageHighlightedTimeout = setTimeout(() => {
        setHighLightedMessageId(0);
        onMessageHighlighted === null || onMessageHighlighted === void 0 ? void 0 : onMessageHighlighted();
      }, 1600);
    } else {
      setIsHighlighted(false);
    }
    return () => {
      clearTimeout(animationTimeout);
      clearTimeout(messageHighlightedTimeout);
    };
  }, [highLightedMessageId, messageScrollRef.current, message.messageId]);
  useLayoutEffect(() => {
    let animationTimeout = null;
    let messageAnimatedTimeout = null;
    if (animatedMessageId === message.messageId && messageScrollRef !== null && messageScrollRef !== void 0 && messageScrollRef.current) {
      handleOnScroll();
      setIsHighlighted(false);
      animationTimeout = setTimeout(() => {
        setIsAnimated(true);
      }, 500);
      messageAnimatedTimeout = setTimeout(() => {
        setAnimatedMessageId(0);
        onMessageAnimated === null || onMessageAnimated === void 0 ? void 0 : onMessageAnimated();
      }, 1600);
    } else {
      setIsAnimated(false);
    }
    return () => {
      clearTimeout(animationTimeout);
      clearTimeout(messageAnimatedTimeout);
    };
  }, [animatedMessageId, messageScrollRef.current, message.messageId, onMessageAnimated]);
  const renderedMessage = useMemo(() => {
    return renderMessage === null || renderMessage === void 0 ? void 0 : renderMessage({
      message,
      chainTop,
      chainBottom
    });
  }, [message, renderMessage]);
  const renderedCustomSeparator = useMemo(() => {
    if (renderCustomSeparator) {
      return renderCustomSeparator === null || renderCustomSeparator === void 0 ? void 0 : renderCustomSeparator({
        message: message
      });
    }
    return null;
  }, [message, renderCustomSeparator]);
  if (renderedMessage) {
    return /*#__PURE__*/React__default.createElement("div", {
      // do not delete this data attribute, used for scroll to given message
      // and also for testing
      "data-sb-message-id": message.messageId,
      "data-sb-created-at": message.createdAt,
      ref: messageScrollRef,
      className: getClassName(['sendbird-msg-hoc sendbird-msg--scroll-ref', isAnimated ? 'sendbird-msg-hoc__animated' : '', isHighlighted ? 'sendbird-msg-hoc__highlighted' : ''])
    },
    // TODO: Add message instance as a function parameter
    hasSeparator && (renderedCustomSeparator || /*#__PURE__*/React__default.createElement(DateSeparator, null, /*#__PURE__*/React__default.createElement(Label, {
      type: LabelTypography.CAPTION_2,
      color: LabelColors.ONBACKGROUND_2
    }, format(message.createdAt, 'MMMM dd, yyyy', {
      locale: dateLocale
    })))), renderedMessage);
  }
  if (showEdit && message !== null && message !== void 0 && (_message$isUserMessag = message.isUserMessage) !== null && _message$isUserMessag !== void 0 && _message$isUserMessag.call(message)) {
    return (renderEditInput === null || renderEditInput === void 0 ? void 0 : renderEditInput()) || /*#__PURE__*/React__default.createElement(React__default.Fragment, null, displaySuggestedMentionList && /*#__PURE__*/React__default.createElement(SuggestedMentionList, {
      targetNickname: mentionNickname,
      inputEvent: messageInputEvent,
      renderUserMentionItem: renderUserMentionItem,
      onUserItemClick: user => {
        if (user) {
          setMentionedUsers([...mentionedUsers, user]);
        }
        setMentionNickname('');
        setSelectedUser(user);
        setMessageInputEvent(null);
      },
      onFocusItemChange: () => {
        setMessageInputEvent(null);
      },
      onFetchUsers: users => {
        setMentionSuggestedUsers(users);
      },
      ableAddMention: ableMention,
      maxMentionCount: maxUserMentionCount,
      maxSuggestionCount: maxUserSuggestionCount
    }), /*#__PURE__*/React__default.createElement(MessageInput, {
      isEdit: true,
      channel: currentGroupChannel,
      disabled: disabled,
      ref: editMessageInputRef,
      mentionSelectedUser: selectedUser,
      isMentionEnabled: isMentionEnabled,
      message: message,
      onStartTyping: () => {
        var _currentGroupChannel$2;
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$2 = currentGroupChannel.startTyping) === null || _currentGroupChannel$2 === void 0 ? void 0 : _currentGroupChannel$2.call(currentGroupChannel);
      },
      onUpdateMessage: _ref3 => {
        var _currentGroupChannel$3;
        let {
          messageId,
          message,
          mentionTemplate
        } = _ref3;
        updateMessage({
          messageId,
          message,
          mentionedUsers,
          mentionTemplate
        });
        setShowEdit(false);
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$3 = currentGroupChannel.endTyping) === null || _currentGroupChannel$3 === void 0 ? void 0 : _currentGroupChannel$3.call(currentGroupChannel);
      },
      onCancelEdit: () => {
        var _currentGroupChannel$4;
        setMentionNickname('');
        setMentionedUsers([]);
        setMentionedUserIds([]);
        setMentionSuggestedUsers([]);
        setShowEdit(false);
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$4 = currentGroupChannel.endTyping) === null || _currentGroupChannel$4 === void 0 ? void 0 : _currentGroupChannel$4.call(currentGroupChannel);
      },
      onUserMentioned: user => {
        if ((selectedUser === null || selectedUser === void 0 ? void 0 : selectedUser.userId) === (user === null || user === void 0 ? void 0 : user.userId)) {
          setSelectedUser(null);
          setMentionNickname('');
        }
      },
      onMentionStringChange: mentionText => {
        setMentionNickname(mentionText);
      },
      onMentionedUserIdsUpdated: userIds => {
        setMentionedUserIds(userIds);
      },
      onKeyDown: e => {
        if (displaySuggestedMentionList && (mentionSuggestedUsers === null || mentionSuggestedUsers === void 0 ? void 0 : mentionSuggestedUsers.length) > 0 && (e.key === MessageInputKeys.Enter && ableMention || e.key === MessageInputKeys.ArrowUp || e.key === MessageInputKeys.ArrowDown)) {
          setMessageInputEvent(e);
          return true;
        }
        return false;
      }
    }));
  }
  return /*#__PURE__*/React__default.createElement("div", {
    className: getClassName(['sendbird-msg-hoc sendbird-msg--scroll-ref', isAnimated ? 'sendbird-msg-hoc__animated' : '', isHighlighted ? 'sendbird-msg-hoc__highlighted' : '']),
    style: {
      marginBottom: '2px'
    },
    "data-sb-message-id": message.messageId,
    "data-sb-created-at": message.createdAt,
    ref: messageScrollRef
  }, hasSeparator && (renderedCustomSeparator || /*#__PURE__*/React__default.createElement(DateSeparator, null, /*#__PURE__*/React__default.createElement(Label, {
    type: LabelTypography.CAPTION_2,
    color: LabelColors.ONBACKGROUND_2
  }, format(message.createdAt, 'MMMM dd, yyyy', {
    locale: dateLocale
  })))), (renderMessageContent === null || renderMessageContent === void 0 ? void 0 : renderMessageContent()) || /*#__PURE__*/React__default.createElement(MessageContent, {
    className: "sendbird-message-hoc__message-content",
    userId: userId,
    scrollToMessage: scrollToMessage,
    channel: currentGroupChannel,
    message: message,
    disabled: !isOnline,
    chainTop: chainTop,
    chainBottom: chainBottom,
    isReactionEnabled: isReactionEnabled,
    replyType: replyType,
    threadReplySelectType: threadReplySelectType,
    nicknamesMap: nicknamesMap,
    emojiContainer: emojiContainer,
    showEdit: setShowEdit,
    showRemove: setShowRemove,
    showFileViewer: setShowFileViewer,
    resendMessage: resendMessage,
    toggleReaction: toggleReaction,
    setQuoteMessage: setQuoteMessage,
    onReplyInThread: onReplyInThread,
    onQuoteMessageClick: onQuoteMessageClick,
    onMessageHeightChange: handleScroll
  }), showRemove && /*#__PURE__*/React__default.createElement(RemoveMessage, {
    message: message,
    onCancel: () => setShowRemove(false)
  }), showFileViewer && /*#__PURE__*/React__default.createElement(FileViewer, {
    message: message,
    onCancel: () => setShowFileViewer(false)
  }));
};

export { Message as default };
//# sourceMappingURL=Message.js.map
