import React__default, { useState, useEffect, useRef, useLayoutEffect, useMemo } from 'react';
import { f as format } from '../../index-2dc53ac2.js';
import SuggestedMentionList from './SuggestedMentionList.js';
import useSendbirdStateContext from '../../useSendbirdStateContext.js';
import { u as useChannelContext, a as isDisabledBecauseFrozen, b as isDisabledBecauseMuted } from '../../ChannelProvider-498954bf.js';
import { h as getClassName } from '../../index-eefb44ba.js';
import { M as MAX_USER_MENTION_COUNT, a as MAX_USER_SUGGESTION_COUNT } from '../../const-97fac210.js';
import DateSeparator from '../../ui/DateSeparator.js';
import { L as Label, a as LabelTypography, b as LabelColors } from '../../index-4372fcec.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-922f4cc5.js';
import { u as useLocalization } from '../../LocalizationContext-b2390bf8.js';
import { a as useHandleOnScrollCallback } from '../../index-28ad85ee.js';
import { u as useDirtyGetMentions } from '../../useDirtyGetMentions-5f675b6c.js';
import '../../index-67135027.js';
import '../../ui/Icon.js';
import 'prop-types';
import '../../ui/Avatar.js';
import '../../ui/ImageRenderer.js';
import '../../uuid-a79b5ba8.js';
import '../../ThreadProvider-2bdeb95d.js';
import '../../utils/message/getOutgoingMessageState.js';
import '../../UserProfileContext-d5787c95.js';
import '../../_rollupPluginBabelHelpers-4f8ebde4.js';
import '../../Thread/context/types.js';
import '@sendbird/chat';
import '../../topics-f3629ea0.js';
import '@sendbird/chat/groupChannel';
import '@sendbird/chat/message';
import '../../consts-33537265.js';
import '../../withSendbird.js';
import '../../compareIds-7800035f.js';
import '../../resolvedReplyType-e00d5fd9.js';
import '../../color-9519a526.js';
import '../../stringSet-eefbc798.js';
import '../../ui/IconButton.js';
import '../../ui/Button.js';
import 'dompurify';
import '../../consts-8ce876a0.js';
import '../../consts-e3e03145.js';
import '../../consts-cdccf171.js';
import '../../tokenize-b97bc343.js';
import '../../index.module-2885df8c.js';
import '../../ui/UserProfile.js';
import '../../sendbirdSelectors.js';
import '../../utils-b53fe532.js';
import '../../index-1d741554.js';
import '../../ui/Loader.js';
import '../../index-0d1114ee.js';
import '../../index-39306dfb.js';
import '../../ui/MessageItemMenu.js';
import '../../ui/ContextMenu.js';
import 'react-dom';
import '../../ui/SortByRow.js';
import '../../types-234b17b9.js';
import '../../ui/MessageItemReactionMenu.js';
import '../../ui/ReactionButton.js';
import '../../useLongPress-cb2d23be.js';
import '../../MediaQueryContext-b4904a2e.js';
import '../../ui/EmojiReactions.js';
import '../../ui/ReactionBadge.js';
import '../../ui/BottomSheet.js';
import '../../index-896545a0.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-8aa7880e.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-484b4a5d.js';
import '../../ui/ThreadReplies.js';
import '../../ui/VoiceMessageItemBody.js';
import '../../ui/ProgressBar.js';
import '../../VoicePlayer/useVoicePlayer.js';
import '../../index-7d496661.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,
    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]);
  useLayoutEffect(() => {
    // Keep the scrollBottom value after fetching new message list
    handleScroll === null || handleScroll === void 0 ? void 0 : handleScroll();
  }, []);
  /**
   * Move the messsage list scroll
   * when the message's height is changed by `showEdit` OR `message.reactions`
   */
  useDidMountEffect(() => {
    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]);
  useDidMountEffect(() => {
    handleScroll === null || handleScroll === void 0 ? void 0 : handleScroll(true);
  }, [message === null || message === void 0 ? void 0 : message.updatedAt]);
  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$;
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$ = currentGroupChannel.startTyping) === null || _currentGroupChannel$ === void 0 ? void 0 : _currentGroupChannel$.call(currentGroupChannel);
      },
      onUpdateMessage: _ref3 => {
        var _currentGroupChannel$2;
        let {
          messageId,
          message,
          mentionTemplate
        } = _ref3;
        updateMessage({
          messageId,
          message,
          mentionedUsers,
          mentionTemplate
        });
        setShowEdit(false);
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$2 = currentGroupChannel.endTyping) === null || _currentGroupChannel$2 === void 0 ? void 0 : _currentGroupChannel$2.call(currentGroupChannel);
      },
      onCancelEdit: () => {
        var _currentGroupChannel$3;
        setMentionNickname('');
        setMentionedUsers([]);
        setMentionedUserIds([]);
        setMentionSuggestedUsers([]);
        setShowEdit(false);
        currentGroupChannel === null || currentGroupChannel === void 0 ? void 0 : (_currentGroupChannel$3 = currentGroupChannel.endTyping) === null || _currentGroupChannel$3 === void 0 ? void 0 : _currentGroupChannel$3.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
