'use strict';

var React = require('react');
var ui_Label = require('../../index-2bfd366f.js');
var ui_Icon = require('../../ui/Icon.js');
var ui_Avatar = require('../../ui/Avatar.js');
var LocalizationContext = require('../../LocalizationContext-44d2f61b.js');
var uuid = require('../../uuid-dee74248.js');
var Channel_context = require('../../ChannelProvider-a05d259f.js');
var useSendbirdStateContext = require('../../useSendbirdStateContext.js');
var _const$1 = require('../../const-1ea78727.js');
var _const = require('../../const-bd02657f.js');
var Thread_context = require('../../ThreadProvider-bac1bea8.js');
require('prop-types');
require('../../stringSet-7aebf034.js');
require('../../ui/ImageRenderer.js');
require('../../index-88e8fdfa.js');
require('../../UserProfileContext-9d843d68.js');
require('../../index-892b4b7f.js');
require('../../topics-373d2156.js');
require('../../index-1b3c69da.js');
require('../../_rollupPluginBabelHelpers-21ae158b.js');
require('../../utils/message/getOutgoingMessageState.js');
require('../../compareIds-a846891d.js');
require('@sendbird/chat/groupChannel');
require('@sendbird/chat/message');
require('../../consts-900e72b9.js');
require('../../resolvedReplyType-14fa0f85.js');
require('../../withSendbird.js');
require('../../Thread/context/types.js');
require('@sendbird/chat');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

function SuggestedUserMentionItem(props) {
  const {
    member,
    isFocused = false,
    parentScrollRef,
    onClick,
    onMouseOver,
    onMouseMove,
    renderUserMentionItem
  } = props;
  const scrollRef = React.useRef(null);
  const {
    stringSet = {}
  } = React.useContext(LocalizationContext.LocalizationContext);
  React.useEffect(() => {
    if (isFocused && (parentScrollRef === null || parentScrollRef === void 0 ? void 0 : parentScrollRef.current) != null && (scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) != null && (parentScrollRef.current.scrollTop >= scrollRef.current.offsetTop || parentScrollRef.current.scrollTop + parentScrollRef.current.clientHeight <= scrollRef.current.offsetTop)) {
      scrollRef.current.scrollIntoView({
        block: 'nearest',
        inline: 'nearest'
      });
    }
  }, [isFocused]);
  const customMentionItem = React.useMemo(() => {
    if (renderUserMentionItem) {
      return /*#__PURE__*/React__default["default"].createElement("div", {
        className: "sendbird-mention-suggest-list__user-item",
        onClick: event => onClick === null || onClick === void 0 ? void 0 : onClick({
          event,
          member: member,
          itemRef: scrollRef
        }),
        onMouseOver: event => onMouseOver === null || onMouseOver === void 0 ? void 0 : onMouseOver({
          event,
          member: member,
          itemRef: scrollRef
        }),
        onMouseMove: event => onMouseMove === null || onMouseMove === void 0 ? void 0 : onMouseMove({
          event,
          member: member,
          itemRef: scrollRef
        }),
        key: (member === null || member === void 0 ? void 0 : member.userId) || uuid.uuidv4(),
        ref: scrollRef
      }, renderUserMentionItem({
        user: member
      }));
    }
  }, [renderUserMentionItem]);
  if (customMentionItem) {
    return customMentionItem;
  }
  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: `sendbird-mention-suggest-list__user-item ${isFocused ? 'focused' : ''}`,
    onClick: event => onClick === null || onClick === void 0 ? void 0 : onClick({
      event,
      member: member,
      itemRef: scrollRef
    }),
    onMouseOver: event => onMouseOver === null || onMouseOver === void 0 ? void 0 : onMouseOver({
      event,
      member: member,
      itemRef: scrollRef
    }),
    onMouseMove: event => onMouseMove === null || onMouseMove === void 0 ? void 0 : onMouseMove({
      event,
      member: member,
      itemRef: scrollRef
    }),
    key: (member === null || member === void 0 ? void 0 : member.userId) || uuid.uuidv4(),
    ref: scrollRef
  }, /*#__PURE__*/React__default["default"].createElement(ui_Avatar["default"], {
    className: "sendbird-mention-suggest-list__user-item__avatar",
    src: member === null || member === void 0 ? void 0 : member.profileUrl,
    alt: "user-profile",
    width: "24px",
    height: "24px"
  }), /*#__PURE__*/React__default["default"].createElement(ui_Label.Label, {
    className: "sendbird-mention-suggest-list__user-item__nickname",
    type: ui_Label.LabelTypography.SUBTITLE_2,
    color: member !== null && member !== void 0 && member.nickname ? ui_Label.LabelColors.ONBACKGROUND_1 : ui_Label.LabelColors.ONBACKGROUND_3
  }, (member === null || member === void 0 ? void 0 : member.nickname) || (stringSet === null || stringSet === void 0 ? void 0 : stringSet.MENTION_NAME__NO_NAME)), /*#__PURE__*/React__default["default"].createElement(ui_Label.Label, {
    className: "sendbird-mention-suggest-list__user-item__user-id",
    type: ui_Label.LabelTypography.SUBTITLE_2,
    color: ui_Label.LabelColors.ONBACKGROUND_2
  }, member === null || member === void 0 ? void 0 : member.userId));
}

const DEBOUNCING_TIME = 300;
function SuggestedMentionList(props) {
  var _useChannelContext, _useThreadContext, _stores$sdkStore, _stores$sdkStore$sdk, _stores$sdkStore$sdk$;
  const {
    className,
    targetNickname = '',
    // memberListQuery,
    onUserItemClick,
    onFocusItemChange,
    onFetchUsers,
    renderUserMentionItem,
    inputEvent,
    ableAddMention = true,
    maxMentionCount = _const$1.MAX_USER_MENTION_COUNT,
    maxSuggestionCount = _const$1.MAX_USER_SUGGESTION_COUNT
  } = props;
  const currentGroupChannel = Channel_context.useChannelContext === null || Channel_context.useChannelContext === void 0 ? void 0 : (_useChannelContext = Channel_context.useChannelContext()) === null || _useChannelContext === void 0 ? void 0 : _useChannelContext.currentGroupChannel;
  const currentChannel = Thread_context.useThreadContext === null || Thread_context.useThreadContext === void 0 ? void 0 : (_useThreadContext = Thread_context.useThreadContext()) === null || _useThreadContext === void 0 ? void 0 : _useThreadContext.currentChannel;
  const channelInstance = currentGroupChannel || currentChannel;
  const {
    config,
    stores
  } = useSendbirdStateContext();
  const {
    logger
  } = config;
  const currentUserId = (stores === null || stores === void 0 ? void 0 : (_stores$sdkStore = stores.sdkStore) === null || _stores$sdkStore === void 0 ? void 0 : (_stores$sdkStore$sdk = _stores$sdkStore.sdk) === null || _stores$sdkStore$sdk === void 0 ? void 0 : (_stores$sdkStore$sdk$ = _stores$sdkStore$sdk.currentUser) === null || _stores$sdkStore$sdk$ === void 0 ? void 0 : _stores$sdkStore$sdk$.userId) || '';
  const scrollRef = React.useRef(null);
  const {
    stringSet
  } = React.useContext(LocalizationContext.LocalizationContext);
  const [timer, setTimer] = React.useState(null);
  const [searchString, setSearchString] = React.useState('');
  const [lastSearchString, setLastSearchString] = React.useState('');
  const [currentUser, setCurrentUser] = React.useState(null);
  const [currentMemberList, setCurrentMemberList] = React.useState([]);
  React.useEffect(() => {
    clearTimeout(timer);
    setTimer(setTimeout(() => {
      setSearchString(targetNickname);
    }, DEBOUNCING_TIME));
  }, [targetNickname]);
  React.useEffect(() => {
    if ((inputEvent === null || inputEvent === void 0 ? void 0 : inputEvent.key) === _const.MessageInputKeys.Enter) {
      if (currentMemberList.length > 0) {
        onUserItemClick(currentUser);
      }
    }
    if ((inputEvent === null || inputEvent === void 0 ? void 0 : inputEvent.key) === _const.MessageInputKeys.ArrowUp) {
      const currentUserIndex = currentMemberList.findIndex(member => (member === null || member === void 0 ? void 0 : member.userId) === (currentUser === null || currentUser === void 0 ? void 0 : currentUser.userId));
      if (0 < currentUserIndex) {
        setCurrentUser(currentMemberList[currentUserIndex - 1]);
        onFocusItemChange(currentMemberList[currentUserIndex - 1]);
      }
    }
    if ((inputEvent === null || inputEvent === void 0 ? void 0 : inputEvent.key) === _const.MessageInputKeys.ArrowDown) {
      const currentUserIndex = currentMemberList.findIndex(member => (member === null || member === void 0 ? void 0 : member.userId) === (currentUser === null || currentUser === void 0 ? void 0 : currentUser.userId));
      if (currentUserIndex < currentMemberList.length - 1) {
        setCurrentUser(currentMemberList[currentUserIndex + 1]);
        onFocusItemChange(currentMemberList[currentUserIndex + 1]);
      }
    }
  }, [inputEvent]);

  /* Fetch member list */
  React.useEffect(() => {
    if (!(channelInstance !== null && channelInstance !== void 0 && channelInstance.createMemberListQuery)) {
      logger.warning('SuggestedMentionList: Creating member list query failed');
      return;
    }
    if (lastSearchString && searchString.indexOf(lastSearchString) === 0 && currentMemberList.length === 0) {
      // Don't need to request query again
      return;
    }
    const query = channelInstance === null || channelInstance === void 0 ? void 0 : channelInstance.createMemberListQuery({
      limit: maxSuggestionCount + 1,
      // because current user could be included
      nicknameStartsWithFilter: searchString.slice(_const$1.USER_MENTION_TEMP_CHAR.length)
    });
    // Add member list query for customization
    query.next().then(memberList => {
      const suggestingMembers = memberList.filter(member => currentUserId !== (member === null || member === void 0 ? void 0 : member.userId)).slice(0, maxSuggestionCount);
      if (suggestingMembers.length < 1) {
        logger.info('SuggestedMentionList: Fetched member list is empty');
      } else {
        logger.info('SuggestedMentionList: Fetching member list succeeded', {
          memberListQuery: query,
          memberList: suggestingMembers
        });
        setCurrentUser(suggestingMembers[0]);
      }
      setLastSearchString(searchString);
      onFetchUsers(suggestingMembers);
      setCurrentMemberList(suggestingMembers);
    }).catch(error => {
      if (error) {
        logger.error('SuggestedMentionList: Fetching member list failed', error);
      }
    });
  }, [channelInstance === null || channelInstance === void 0 ? void 0 : channelInstance.url, searchString]);
  if (!ableAddMention && currentMemberList.length === 0) {
    return null;
  }
  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: `sendbird-mention-suggest-list ${className}`,
    key: "sendbird-mention-suggest-list",
    ref: scrollRef
  }, ableAddMention && (currentMemberList === null || currentMemberList === void 0 ? void 0 : currentMemberList.map(member => /*#__PURE__*/React__default["default"].createElement(SuggestedUserMentionItem, {
    key: (member === null || member === void 0 ? void 0 : member.userId) || uuid.uuidv4(),
    member: member,
    isFocused: (member === null || member === void 0 ? void 0 : member.userId) === (currentUser === null || currentUser === void 0 ? void 0 : currentUser.userId),
    parentScrollRef: scrollRef,
    onClick: _ref => {
      let {
        member
      } = _ref;
      onUserItemClick(member);
    },
    onMouseOver: _ref2 => {
      let {
        member
      } = _ref2;
      setCurrentUser(member);
    },
    renderUserMentionItem: renderUserMentionItem
  }))), !ableAddMention && /*#__PURE__*/React__default["default"].createElement("div", {
    className: "sendbird-mention-suggest-list__notice-item"
  }, /*#__PURE__*/React__default["default"].createElement(ui_Icon["default"], {
    className: "sendbird-mention-suggest-list__notice-item__icon",
    type: ui_Icon.IconTypes.INFO,
    fillColor: ui_Icon.IconColors.ON_BACKGROUND_2,
    width: "20px",
    height: "20px"
  }), /*#__PURE__*/React__default["default"].createElement(ui_Label.Label, {
    className: "sendbird-mention-suggest-list__notice-item__text",
    type: ui_Label.LabelTypography.SUBTITLE_2,
    color: ui_Label.LabelColors.ONBACKGROUND_2
  }, stringSet.MENTION_COUNT__OVER_LIMIT.replace('%d', maxMentionCount))));
}

module.exports = SuggestedMentionList;
//# sourceMappingURL=SuggestedMentionList.js.map
