"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _reactNative = require("react-native");
var _react = require("react");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _CommentListItem = _interopRequireDefault(require("../CommentListItem/CommentListItem"));
var _comment = require("../../../../core/legacy/comment");
var _styles = require("./styles");
var _reactNativePaper = require("react-native-paper");
var _xml = require("../../../../core/assets/icons/xml");
var _reactNativeSvg = require("react-native-svg");
var _usePaginator = require("../../../hooks/usePaginator");
var _useCustomRankingGlobalFeed = require("../../../hooks/useCustomRankingGlobalFeed");
var _CommentAdComponent = _interopRequireDefault(require("../../CommentAdComponent/CommentAdComponent"));
var _useMention = _interopRequireDefault(require("../../../hooks/useMention"));
var _reactNativeControlledMentions = require("react-native-controlled-mentions");
var _MyAvatar = _interopRequireDefault(require("../../MyAvatar/MyAvatar"));
var _toastSlice = require("../../../../core/stores/slices/toastSlice");
var _icons = require("../../../../core/assets/icons");
var _Typography = require("../../../../core/components/Typography/Typography");
var _constants = require("../../../../core/constants");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const commentListLimit = 8;
const CommentList = ({
  postId,
  postType,
  disabledInteraction,
  onNavigate,
  withAvatar,
  disabledComment
}) => {
  const styles = (0, _styles.useStyles)();
  const theme = (0, _reactNativePaper.useTheme)();
  const onNextPageRef = (0, _react.useRef)(null);
  const [commentList, setCommentList] = (0, _react.useState)([]);
  const [loadingComments, setLoadingComments] = (0, _react.useState)(true);
  const [replyUserName, setReplyUserName] = (0, _react.useState)('');
  const [replyCommentId, setReplyCommentId] = (0, _react.useState)('');
  const [inputMessage, setInputMessage] = (0, _react.useState)('');
  const [mentionNames, setMentionNames] = (0, _react.useState)([]);
  const [mentionsPosition, setMentionsPosition] = (0, _react.useState)([]);
  const [inputBarHeight, setInputBarHeight] = (0, _react.useState)(0);
  const {
    showCommentErrorToast
  } = (0, _toastSlice.useToast)();
  const {
    renderInput,
    renderSuggestions
  } = (0, _useMention.default)({
    value: inputMessage,
    onChange: setInputMessage,
    setMentionUsers: user => {
      setMentionNames(prev => {
        if (prev.some(mentionedUser => mentionedUser.id === user.id)) {
          return prev;
        }
        if (prev.length >= _constants.MAX_MENTION_USERS) {
          _reactNative.Alert.alert('Too many users mentioned', `You can only mention up to ${_constants.MAX_MENTION_USERS} users per post.`, [{
            text: 'OK'
          }]);
          return prev;
        }
        return [...prev, user];
      });
    },
    setMentionPosition: position => {
      setMentionsPosition(prev => [...prev, position]);
    }
  });
  const {
    itemWithAds
  } = (0, _usePaginator.usePaginatorApi)({
    items: commentList,
    placement: 'comment',
    pageSize: commentListLimit,
    getItemId: item => item.commentId
  });
  (0, _react.useEffect)(() => {
    _tsSdkReactNative.CommentRepository.getComments({
      dataTypes: {
        matchType: 'any',
        values: ['text', 'image']
      },
      referenceId: postId,
      referenceType: postType,
      limit: commentListLimit
    }, ({
      error,
      loading,
      data,
      hasNextPage,
      onNextPage
    }) => {
      setLoadingComments(loading);
      if (error) return;
      if (!loading) {
        data && data.length > 0 && queryComment(data);
        onNextPageRef.current = hasNextPage ? onNextPage : null;
      }
    });
    return () => {
      setCommentList([]);
    };
  }, [postId, postType]);
  (0, _react.useEffect)(() => {
    // Parse active mention user IDs directly from the controlled-mentions
    // value format: {@}[DisplayName](userId)
    // Using displayName.includes() is unreliable — the same name can appear as
    // plain text, and deletions may not remove the entry correctly.
    const mentionTokenRegex = /\{@\}\[([^\]]*)\]\(([^)]*)\)/g;
    const activeUserIds = new Set();
    let match;
    while ((match = mentionTokenRegex.exec(inputMessage)) !== null) {
      activeUserIds.add(match[2]); // userId is capture group 2
    }
    setMentionNames(prev => prev.filter(item => activeUserIds.has(item.id)));
    setMentionsPosition(prev => prev.filter(item => activeUserIds.has(item.userId)));
  }, [inputMessage]);
  const queryComment = async comments => {
    const formattedCommentList = comments.map(item => {
      var _item$creator, _item$creator2, _item$creator3, _item$metadata;
      let formattedUserObject;
      formattedUserObject = {
        userId: item === null || item === void 0 || (_item$creator = item.creator) === null || _item$creator === void 0 ? void 0 : _item$creator.userId,
        displayName: item === null || item === void 0 || (_item$creator2 = item.creator) === null || _item$creator2 === void 0 ? void 0 : _item$creator2.displayName,
        avatarFileId: item === null || item === void 0 || (_item$creator3 = item.creator) === null || _item$creator3 === void 0 ? void 0 : _item$creator3.avatarFileId
      };
      return {
        commentId: item.commentId,
        data: item.data,
        dataType: item.dataType || 'text',
        myReactions: item.myReactions,
        reactions: item.reactions,
        user: formattedUserObject,
        updatedAt: item.updatedAt,
        editedAt: item.editedAt,
        createdAt: item.createdAt,
        childrenComment: item.children,
        childrenNumber: item.childrenNumber,
        referenceId: item.referenceId,
        mentionPosition: (item === null || item === void 0 || (_item$metadata = item.metadata) === null || _item$metadata === void 0 ? void 0 : _item$metadata.mentioned) ?? []
      };
    });
    setCommentList([...formattedCommentList]);
  };
  const onDeleteComment = async commentId => {
    const isDeleted = await (0, _comment.deleteCommentById)(commentId);
    if (isDeleted) {
      const prevCommentList = [...commentList];
      const updatedCommentList = prevCommentList.filter(item => item.commentId !== commentId);
      setCommentList(updatedCommentList);
    }
  };
  const handleClickReply = (user, commentId) => {
    setReplyUserName(user.displayName);
    setReplyCommentId(commentId);
  };
  const onCloseReply = () => {
    setReplyUserName('');
    setReplyCommentId('');
  };
  const handleSend = async () => {
    if (inputMessage.trim() === '') {
      return;
    }
    if (mentionNames.length > _constants.MAX_MENTION_USERS) {
      _reactNative.Alert.alert('Too many users mentioned', 'You can only mention up to 30 users per post.', [{
        text: 'OK'
      }]);
      return;
    }
    const comment = (0, _reactNativeControlledMentions.replaceTriggerValues)(inputMessage, ({
      name
    }) => `@${name}`);
    if (replyCommentId.length > 0) {
      try {
        await (0, _comment.createReplyComment)(comment, postId, replyCommentId, mentionNames === null || mentionNames === void 0 ? void 0 : mentionNames.map(item => item.id), mentionsPosition, postType);
      } catch (error) {
        showCommentErrorToast(error);
        return;
      }
    } else {
      try {
        await (0, _comment.createComment)(comment, postId, mentionNames === null || mentionNames === void 0 ? void 0 : mentionNames.map(item => item.id), mentionsPosition, postType);
      } catch (error) {
        showCommentErrorToast(error);
        return;
      }
    }
    setInputMessage('');
    _reactNative.Keyboard.dismiss();
    setMentionNames([]);
    setMentionsPosition([]);
    onCloseReply();
  };
  const renderFooterComponent = () => {
    return /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.commentListFooter
    }, renderSuggestions({
      type: 'comment',
      style: styles.suggestionContainer,
      bottom: inputBarHeight
    }), /*#__PURE__*/React.createElement(_reactNative.View, {
      onLayout: e => setInputBarHeight(e.nativeEvent.layout.height)
    }, replyUserName.length > 0 && /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.replyLabelWrap
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.replyLabel
    }, "Replying to", ' ', /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.userNameLabel
    }, replyUserName)), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, null, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      onPress: onCloseReply
    }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
      style: styles.closeIcon,
      xml: (0, _xml.closeIcon)(theme.colors.baseShade2),
      width: 20
    })))), !disabledInteraction && (disabledComment ? /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.disabledCommentWrap
    }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
      width: 20,
      height: 20,
      xml: (0, _icons.lock)(),
      color: theme.colors.baseShade2
    }), /*#__PURE__*/React.createElement(_Typography.Typography.Body, {
      style: styles.disabledCommentText
    }, "Comments are disabled for this story")) : /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.inputWrap
    }, withAvatar && /*#__PURE__*/React.createElement(_MyAvatar.default, null), /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.inputContainer
    }, renderInput({
      multiline: true,
      scrollEnabled: true,
      style: [styles.textInput, {
        lineHeight: 20
      }],
      placeholder: 'Say something nice...',
      placeholderTextColor: theme.colors.baseShade3
    })), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      disabled: inputMessage.length > 0 ? false : true,
      onPress: handleSend,
      style: styles.postBtn
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: inputMessage.length > 0 ? styles.postBtnText : styles.postDisabledBtn
    }, "Post"))))));
  };
  return /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.root
  }, /*#__PURE__*/React.createElement(_reactNative.FlatList, {
    keyboardShouldPersistTaps: "handled",
    data: itemWithAds,
    contentContainerStyle: styles.listContent,
    renderItem: ({
      item
    }) => {
      if ((0, _useCustomRankingGlobalFeed.isAmityAd)(item)) {
        return /*#__PURE__*/React.createElement(_CommentAdComponent.default, {
          ad: item
        });
      }
      return /*#__PURE__*/React.createElement(_CommentListItem.default, {
        onDelete: onDeleteComment,
        commentDetail: item,
        onClickReply: handleClickReply,
        postType: postType,
        disabledComment: disabledComment,
        disabledInteraction: disabledInteraction,
        onNavigate: onNavigate
      });
    },
    keyExtractor: (item, index) => ((0, _useCustomRankingGlobalFeed.isAmityAd)(item) ? item.adId : item.commentId) + `_${index}`,
    ListEmptyComponent: loadingComments ? null : /*#__PURE__*/React.createElement(_reactNative.View, {
      style: styles.emptyContainer
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.emptyText
    }, "No comments yet")),
    onEndReachedThreshold: 0.8,
    onEndReached: () => onNextPageRef.current && onNextPageRef.current()
  }), renderFooterComponent());
};
var _default = exports.default = /*#__PURE__*/(0, _react.memo)(CommentList);
//# sourceMappingURL=CommentList.js.map