import React__default, { useRef, useContext, useEffect, useMemo, useState } from 'react';
import { L as Label, a as LabelTypography, b as LabelColors } from '../../index-f50d7ab0.js';
import Icon, { IconTypes, IconColors } from '../../ui/Icon.js';
import Avatar from '../../ui/Avatar.js';
import { a as LocalizationContext } from '../../LocalizationContext-1701e5c8.js';
import { u as uuidv4 } from '../../uuid-8b344dd2.js';
import { u as useChannelContext } from '../../ChannelProvider-1dc36682.js';
import useSendbirdStateContext from '../../useSendbirdStateContext.js';
import { U as USER_MENTION_TEMP_CHAR, M as MAX_USER_MENTION_COUNT, a as MAX_USER_SUGGESTION_COUNT } from '../../const-7c266a95.js';
import { M as MessageInputKeys } from '../../const-2e67461b.js';
import { u as useThreadContext } from '../../ThreadProvider-dea308a0.js';
import 'prop-types';
import '../../stringSet-e9bb0333.js';
import '../../ui/ImageRenderer.js';
import '../../index-ff8f2f61.js';
import '../../UserProfileContext-74e9a128.js';
import '../../index-5a62f6b7.js';
import '../../topics-0b30f52b.js';
import '../../index-99ab01f6.js';
import '../../_rollupPluginBabelHelpers-cc035350.js';
import '../../utils/message/getOutgoingMessageState.js';
import '../../compareIds-367bb030.js';
import '@sendbird/chat/groupChannel';
import '@sendbird/chat/message';
import '../../consts-44eaef6b.js';
import '../../resolvedReplyType-6bb8f548.js';
import '../../withSendbird.js';
import '../../Thread/context/types.js';
import '@sendbird/chat';

function SuggestedUserMentionItem(props) {
  const {
    member,
    isFocused = false,
    parentScrollRef,
    onClick,
    onMouseOver,
    onMouseMove,
    renderUserMentionItem
  } = props;
  const scrollRef = useRef(null);
  const {
    stringSet = {}
  } = useContext(LocalizationContext);
  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 = useMemo(() => {
    if (renderUserMentionItem) {
      return /*#__PURE__*/React__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) || uuidv4(),
        ref: scrollRef
      }, renderUserMentionItem({
        user: member
      }));
    }
  }, [renderUserMentionItem]);
  if (customMentionItem) {
    return customMentionItem;
  }
  return /*#__PURE__*/React__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) || uuidv4(),
    ref: scrollRef
  }, /*#__PURE__*/React__default.createElement(Avatar, {
    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.createElement(Label, {
    className: "sendbird-mention-suggest-list__user-item__nickname",
    type: LabelTypography.SUBTITLE_2,
    color: member !== null && member !== void 0 && member.nickname ? LabelColors.ONBACKGROUND_1 : 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.createElement(Label, {
    className: "sendbird-mention-suggest-list__user-item__user-id",
    type: LabelTypography.SUBTITLE_2,
    color: 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 = MAX_USER_MENTION_COUNT,
    maxSuggestionCount = MAX_USER_SUGGESTION_COUNT
  } = props;
  const currentGroupChannel = useChannelContext === null || useChannelContext === void 0 ? void 0 : (_useChannelContext = useChannelContext()) === null || _useChannelContext === void 0 ? void 0 : _useChannelContext.currentGroupChannel;
  const currentChannel = useThreadContext === null || useThreadContext === void 0 ? void 0 : (_useThreadContext = 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 = useRef(null);
  const {
    stringSet
  } = useContext(LocalizationContext);
  const [timer, setTimer] = useState(null);
  const [searchString, setSearchString] = useState('');
  const [lastSearchString, setLastSearchString] = useState('');
  const [currentUser, setCurrentUser] = useState(null);
  const [currentMemberList, setCurrentMemberList] = useState([]);
  useEffect(() => {
    clearTimeout(timer);
    setTimer(setTimeout(() => {
      setSearchString(targetNickname);
    }, DEBOUNCING_TIME));
  }, [targetNickname]);
  useEffect(() => {
    if ((inputEvent === null || inputEvent === void 0 ? void 0 : inputEvent.key) === MessageInputKeys.Enter) {
      if (currentMemberList.length > 0) {
        onUserItemClick(currentUser);
      }
    }
    if ((inputEvent === null || inputEvent === void 0 ? void 0 : inputEvent.key) === 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) === 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 */
  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(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.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.createElement(SuggestedUserMentionItem, {
    key: (member === null || member === void 0 ? void 0 : member.userId) || 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.createElement("div", {
    className: "sendbird-mention-suggest-list__notice-item"
  }, /*#__PURE__*/React__default.createElement(Icon, {
    className: "sendbird-mention-suggest-list__notice-item__icon",
    type: IconTypes.INFO,
    fillColor: IconColors.ON_BACKGROUND_2,
    width: "20px",
    height: "20px"
  }), /*#__PURE__*/React__default.createElement(Label, {
    className: "sendbird-mention-suggest-list__notice-item__text",
    type: LabelTypography.SUBTITLE_2,
    color: LabelColors.ONBACKGROUND_2
  }, stringSet.MENTION_COUNT__OVER_LIMIT.replace('%d', maxMentionCount))));
}

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