import { Alert, FlatList, Keyboard, Text, TouchableOpacity, View } from 'react-native';
import { useEffect, useState, useRef, memo } from 'react';
import { CommentRepository } from '@amityco/ts-sdk-react-native';
import CommentListItem from '../CommentListItem/CommentListItem';
import { createComment, createReplyComment, deleteCommentById } from '../../../../core/legacy/comment';
import { useStyles } from './styles';
import { useTheme } from 'react-native-paper';
import { closeIcon } from '../../../../core/assets/icons/xml';
import { SvgXml } from 'react-native-svg';
import { usePaginatorApi } from '../../../hooks/usePaginator';
import { isAmityAd } from '../../../hooks/useCustomRankingGlobalFeed';
import CommentAdComponent from '../../CommentAdComponent/CommentAdComponent';
import useMention from '../../../hooks/useMention';
import { replaceTriggerValues } from 'react-native-controlled-mentions';
import MyAvatar from '../../MyAvatar/MyAvatar';
import { useToast } from '../../../../core/stores/slices/toastSlice';
import { lock } from '../../../../core/assets/icons';
import { Typography } from '../../../../core/components/Typography/Typography';
import { MAX_MENTION_USERS } from '../../../../core/constants';
const commentListLimit = 8;
const CommentList = ({
  postId,
  postType,
  disabledInteraction,
  onNavigate,
  withAvatar,
  disabledComment
}) => {
  const styles = useStyles();
  const theme = useTheme();
  const onNextPageRef = useRef(null);
  const [commentList, setCommentList] = useState([]);
  const [loadingComments, setLoadingComments] = useState(true);
  const [replyUserName, setReplyUserName] = useState('');
  const [replyCommentId, setReplyCommentId] = useState('');
  const [inputMessage, setInputMessage] = useState('');
  const [mentionNames, setMentionNames] = useState([]);
  const [mentionsPosition, setMentionsPosition] = useState([]);
  const [inputBarHeight, setInputBarHeight] = useState(0);
  const {
    showCommentErrorToast
  } = useToast();
  const {
    renderInput,
    renderSuggestions
  } = useMention({
    value: inputMessage,
    onChange: setInputMessage,
    setMentionUsers: user => {
      setMentionNames(prev => {
        if (prev.some(mentionedUser => mentionedUser.id === user.id)) {
          return prev;
        }
        if (prev.length >= MAX_MENTION_USERS) {
          Alert.alert('Too many users mentioned', `You can only mention up to ${MAX_MENTION_USERS} users per post.`, [{
            text: 'OK'
          }]);
          return prev;
        }
        return [...prev, user];
      });
    },
    setMentionPosition: position => {
      setMentionsPosition(prev => [...prev, position]);
    }
  });
  const {
    itemWithAds
  } = usePaginatorApi({
    items: commentList,
    placement: 'comment',
    pageSize: commentListLimit,
    getItemId: item => item.commentId
  });
  useEffect(() => {
    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]);
  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 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 > MAX_MENTION_USERS) {
      Alert.alert('Too many users mentioned', 'You can only mention up to 30 users per post.', [{
        text: 'OK'
      }]);
      return;
    }
    const comment = replaceTriggerValues(inputMessage, ({
      name
    }) => `@${name}`);
    if (replyCommentId.length > 0) {
      try {
        await 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 createComment(comment, postId, mentionNames === null || mentionNames === void 0 ? void 0 : mentionNames.map(item => item.id), mentionsPosition, postType);
      } catch (error) {
        showCommentErrorToast(error);
        return;
      }
    }
    setInputMessage('');
    Keyboard.dismiss();
    setMentionNames([]);
    setMentionsPosition([]);
    onCloseReply();
  };
  const renderFooterComponent = () => {
    return /*#__PURE__*/React.createElement(View, {
      style: styles.commentListFooter
    }, renderSuggestions({
      type: 'comment',
      style: styles.suggestionContainer,
      bottom: inputBarHeight
    }), /*#__PURE__*/React.createElement(View, {
      onLayout: e => setInputBarHeight(e.nativeEvent.layout.height)
    }, replyUserName.length > 0 && /*#__PURE__*/React.createElement(View, {
      style: styles.replyLabelWrap
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.replyLabel
    }, "Replying to", ' ', /*#__PURE__*/React.createElement(Text, {
      style: styles.userNameLabel
    }, replyUserName)), /*#__PURE__*/React.createElement(TouchableOpacity, null, /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: onCloseReply
    }, /*#__PURE__*/React.createElement(SvgXml, {
      style: styles.closeIcon,
      xml: closeIcon(theme.colors.baseShade2),
      width: 20
    })))), !disabledInteraction && (disabledComment ? /*#__PURE__*/React.createElement(View, {
      style: styles.disabledCommentWrap
    }, /*#__PURE__*/React.createElement(SvgXml, {
      width: 20,
      height: 20,
      xml: lock(),
      color: theme.colors.baseShade2
    }), /*#__PURE__*/React.createElement(Typography.Body, {
      style: styles.disabledCommentText
    }, "Comments are disabled for this story")) : /*#__PURE__*/React.createElement(View, {
      style: styles.inputWrap
    }, withAvatar && /*#__PURE__*/React.createElement(MyAvatar, null), /*#__PURE__*/React.createElement(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(TouchableOpacity, {
      disabled: inputMessage.length > 0 ? false : true,
      onPress: handleSend,
      style: styles.postBtn
    }, /*#__PURE__*/React.createElement(Text, {
      style: inputMessage.length > 0 ? styles.postBtnText : styles.postDisabledBtn
    }, "Post"))))));
  };
  return /*#__PURE__*/React.createElement(View, {
    style: styles.root
  }, /*#__PURE__*/React.createElement(FlatList, {
    keyboardShouldPersistTaps: "handled",
    data: itemWithAds,
    contentContainerStyle: styles.listContent,
    renderItem: ({
      item
    }) => {
      if (isAmityAd(item)) {
        return /*#__PURE__*/React.createElement(CommentAdComponent, {
          ad: item
        });
      }
      return /*#__PURE__*/React.createElement(CommentListItem, {
        onDelete: onDeleteComment,
        commentDetail: item,
        onClickReply: handleClickReply,
        postType: postType,
        disabledComment: disabledComment,
        disabledInteraction: disabledInteraction,
        onNavigate: onNavigate
      });
    },
    keyExtractor: (item, index) => (isAmityAd(item) ? item.adId : item.commentId) + `_${index}`,
    ListEmptyComponent: loadingComments ? null : /*#__PURE__*/React.createElement(View, {
      style: styles.emptyContainer
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.emptyText
    }, "No comments yet")),
    onEndReachedThreshold: 0.8,
    onEndReached: () => onNextPageRef.current && onNextPageRef.current()
  }), renderFooterComponent());
};
export default /*#__PURE__*/memo(CommentList);
//# sourceMappingURL=CommentList.js.map