import { useEffect, useRef, useState } from 'react';
// import { useTranslation } from 'react-i18next';

import { View, Text, TouchableOpacity, Image, Modal, Animated, Alert, FlatList } from 'react-native';
import { useStyles } from './styles';
import { SvgXml } from 'react-native-svg';
import { expandIcon, likeCircle, likedXml, likeXml, personXml, replyIcon, threeDots } from '../../../../../core/assets/icons/xml';
import { addCommentReaction, removeCommentReaction } from '../../../../../core/legacy/comment';
import { getAmityUser } from '../../../../../core/legacy/user';
import { Pressable } from 'react-native';
import useAuth from '../../../../../core/hooks/useAuth';
import { isReportTarget, reportTargetById, unReportTargetById } from '../../../../../core/legacy/feed';
import EditCommentModal from '../../EditCommentModal';
import { useTheme } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';
import ReplyCommentList from '../ReplyCommentList';
import { CommentRepository } from '@amityco/ts-sdk-react-native';
import { useTimeDifference } from '../../../../../core/hooks/useTimeDifference';
import { LinkPreview } from '../../../PreviewLink/LinkPreview';
const CommentList = ({
  commentDetail,
  onDelete,
  onClickReply
}) => {
  var _previewReplyCommentL;
  const theme = useTheme();
  const styles = useStyles();
  const {
    commentId,
    data,
    user,
    createdAt,
    reactions,
    myReactions,
    childrenComment,
    editedAt,
    mentionPosition,
    childrenNumber,
    referenceId
  } = commentDetail ?? {};
  const timeDifference = useTimeDifference(createdAt);
  const [isLike, setIsLike] = useState(myReactions ? myReactions.includes('like') : false);
  const [likeReaction, setLikeReaction] = useState(reactions !== null && reactions !== void 0 && reactions.like ? reactions === null || reactions === void 0 ? void 0 : reactions.like : 0);
  const {
    client,
    apiRegion
  } = useAuth();
  const [replyCommentList, setReplyCommentList] = useState([]);
  const [previewReplyCommentList, setPreviewReplyCommentList] = useState([]);
  const [replyCommentCollection, setReplyCommentCollection] = useState();
  const {
    onNextPage,
    hasNextPage
  } = replyCommentCollection ?? {};
  const [isOpenReply, setIsOpenReply] = useState(false);
  const [textComment, setTextComment] = useState(data === null || data === void 0 ? void 0 : data.text);
  const [isVisible, setIsVisible] = useState(false);
  const [isReportByMe, setIsReportByMe] = useState(false);
  const [editCommentModal, setEditCommentModal] = useState(false);
  const [isEditComment, setIsEditComment] = useState(false);
  const slideAnimation = useRef(new Animated.Value(0)).current;
  const navigation = useNavigation();
  useEffect(() => {
    getReplyComments();
    setIsOpenReply(true);
    return () => {
      setIsOpenReply(false);
    };
  }, []);
  const openModal = () => {
    setIsVisible(true);
  };
  const closeModal = () => {
    Animated.timing(slideAnimation, {
      toValue: 0,
      duration: 100,
      useNativeDriver: true
    }).start(() => setIsVisible(false));
  };
  const checkIsReport = async () => {
    const isReport = await isReportTarget('comment', commentId);
    if (isReport) {
      setIsReportByMe(true);
    }
  };
  const formatReplyComments = async (replyComments, isPreviewReply = false) => {
    if (isPreviewReply) {
      setPreviewReplyCommentList([]);
    } else {
      setReplyCommentList([]);
    }
    if (replyComments && replyComments.length > 0) {
      const formattedCommentList = await Promise.all(replyComments.map(async item => {
        var _item$metadata;
        const {
          userObject
        } = await getAmityUser(item.userId);
        let formattedUserObject;
        formattedUserObject = {
          userId: userObject.data.userId,
          displayName: userObject.data.displayName,
          avatarFileId: userObject.data.avatarFileId
        };
        return {
          commentId: item.commentId,
          data: item.data,
          dataType: item.dataType,
          myReactions: item.myReactions,
          reactions: item.reactions,
          user: formattedUserObject,
          updatedAt: item.updatedAt,
          editedAt: item.editedAt,
          createdAt: item.createdAt,
          childrenComment: item.children,
          referenceId: item.referenceId,
          mentionPosition: item === null || item === void 0 || (_item$metadata = item.metadata) === null || _item$metadata === void 0 ? void 0 : _item$metadata.mentioned
        };
      }));
      if (isPreviewReply) {
        setPreviewReplyCommentList([...formattedCommentList]);
      } else {
        setReplyCommentList([...formattedCommentList]);
      }
    }
  };
  const getReplyComments = async () => {
    const getCommentsParams = {
      referenceType: 'post',
      referenceId: referenceId,
      // post ID
      dataTypes: {
        values: ['text', 'image'],
        matchType: 'any'
      },
      limit: 3,
      parentId: commentId
    };
    CommentRepository.getComments(getCommentsParams, result => {
      setReplyCommentCollection(result);
      formatReplyComments(result.data);
    });
  };
  const openReplyComment = () => {
    setIsOpenReply(true);
    getReplyComments();
  };
  useEffect(() => {
    checkIsReport();
  }, [childrenComment]);
  const addReactionToComment = async () => {
    if (isLike && likeReaction) {
      setLikeReaction(likeReaction - 1);
      setIsLike(false);
      await removeCommentReaction(commentId, 'like');
    } else {
      setIsLike(true);
      setLikeReaction(likeReaction + 1);
      await addCommentReaction(commentId, 'like');
    }
  };
  const deletePostObject = () => {
    Alert.alert('Delete this post', `This post will be permanently deleted. You'll no longer see and find this post`, [{
      text: 'Cancel',
      style: 'cancel'
    }, {
      text: 'Delete',
      style: 'destructive',
      onPress: () => onDelete && onDelete(commentId)
    }]);
    setIsVisible(false);
  };
  const reportCommentObject = async () => {
    if (isReportByMe) {
      const unReportPost = await unReportTargetById('comment', commentId);
      if (unReportPost) {
        Alert.alert('Undo Report sent');
      }
      setIsVisible(false);
      setIsReportByMe(false);
    } else {
      const reportPost = await reportTargetById('comment', commentId);
      if (reportPost) {
        Alert.alert('Report sent');
      }
      setIsVisible(false);
      setIsReportByMe(true);
    }
  };
  const modalStyle = {
    transform: [{
      translateY: slideAnimation.interpolate({
        inputRange: [0, 1],
        outputRange: [600, 0] // Adjust this value to control the sliding distance
      })
    }]
  };
  const openEditCommentModal = () => {
    setIsVisible(false);
    setEditCommentModal(true);
  };
  const onEditComment = editText => {
    setIsEditComment(true);
    setEditCommentModal(false);
    setTextComment(editText);
  };
  const onCloseEditCommentModal = () => {
    setEditCommentModal(false);
  };
  const onHandleReply = () => {
    onClickReply && onClickReply(user, commentId);
  };
  const onPressCommentReaction = () => {
    navigation.navigate('ReactionList', {
      referenceId: commentId,
      referenceType: 'comment'
    });
  };
  return /*#__PURE__*/React.createElement(View, {
    key: commentId,
    style: styles.commentWrap
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.headerSection
  }, user !== null && user !== void 0 && user.avatarFileId ? /*#__PURE__*/React.createElement(Image, {
    style: styles.avatar,
    source: {
      uri: `https://api.${apiRegion}.amity.co/api/v3/files/${user === null || user === void 0 ? void 0 : user.avatarFileId}/download`
    }
  }) : /*#__PURE__*/React.createElement(View, {
    style: styles.avatar
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: personXml,
    width: "20",
    height: "16"
  })), /*#__PURE__*/React.createElement(View, {
    style: styles.rightSection
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.headerRow
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerText
  }, user === null || user === void 0 ? void 0 : user.displayName)), /*#__PURE__*/React.createElement(View, {
    style: styles.timeRow
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerTextTime
  }, timeDifference), (editedAt !== createdAt || isEditComment) && /*#__PURE__*/React.createElement(Text, {
    style: styles.dot
  }, "\xB7"), (editedAt !== createdAt || isEditComment) && /*#__PURE__*/React.createElement(Text, {
    style: styles.headerTextTime
  }, "Edited")), /*#__PURE__*/React.createElement(View, {
    style: styles.commentBubble
  }, textComment && /*#__PURE__*/React.createElement(LinkPreview, {
    mentionPositionArr: mentionPosition,
    text: textComment
  })), /*#__PURE__*/React.createElement(View, {
    style: styles.actionSection
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => addReactionToComment(),
    style: styles.likeBtn
  }, isLike ? /*#__PURE__*/React.createElement(SvgXml, {
    xml: likedXml(theme.colors.primary),
    width: "20",
    height: "16"
  }) : /*#__PURE__*/React.createElement(SvgXml, {
    xml: likeXml,
    width: "20",
    height: "16"
  }), /*#__PURE__*/React.createElement(Text, {
    style: isLike ? styles.likedText : styles.btnText
  }, !isLike ? 'Like' : 'Liked')), likeReaction > 0 && /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: onPressCommentReaction,
    style: styles.likeBtn
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: likeCircle,
    width: "20",
    height: "16"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.likedText
  }, likeReaction)), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: onHandleReply
    // onPress={() => addReactionToComment()}
    ,
    style: styles.likeBtn
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: replyIcon,
    width: "20",
    height: "16"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.btnText
  }, "Reply")), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: openModal,
    style: styles.threeDots
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: threeDots(theme.colors.base),
    width: "20",
    height: "16"
  }))), previewReplyCommentList.length > 0 && !isOpenReply && /*#__PURE__*/React.createElement(ReplyCommentList, {
    commentId: (_previewReplyCommentL = previewReplyCommentList[previewReplyCommentList.length - 1]) === null || _previewReplyCommentL === void 0 ? void 0 : _previewReplyCommentL.commentId,
    commentDetail: previewReplyCommentList[previewReplyCommentList.length - 1],
    onDelete: onDelete
  }), isOpenReply && /*#__PURE__*/React.createElement(FlatList, {
    data: replyCommentList,
    renderItem: ({
      item
    }) => /*#__PURE__*/React.createElement(ReplyCommentList, {
      commentId: item.commentId,
      commentDetail: item,
      onDelete: onDelete
    }),
    keyExtractor: (item, index) => item.commentId + index
  }), childrenComment.length > 0 && !isOpenReply && /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => openReplyComment(),
    style: styles.viewMoreReplyBtn
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: expandIcon
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.viewMoreText
  }, "View ", childrenNumber, ' ', childrenNumber === 1 ? 'reply' : 'replies')), isOpenReply && hasNextPage && /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => onNextPage(),
    style: styles.viewMoreReplyBtn
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: expandIcon
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.viewMoreText
  }, "View more replies")))), /*#__PURE__*/React.createElement(Modal, {
    animationType: "fade",
    transparent: true,
    visible: isVisible,
    onRequestClose: closeModal
  }, /*#__PURE__*/React.createElement(Pressable, {
    onPress: closeModal,
    style: styles.modalContainer
  }, /*#__PURE__*/React.createElement(Animated.View, {
    style: [styles.modalContent, modalStyle, (user === null || user === void 0 ? void 0 : user.userId) === client.userId && styles.twoOptions]
  }, (user === null || user === void 0 ? void 0 : user.userId) === client.userId ? /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: openEditCommentModal,
    style: styles.modalRow
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.deleteText
  }, " Edit Comment")), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: deletePostObject,
    style: styles.modalRow
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.deleteText
  }, " Delete Comment"))) : /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: reportCommentObject,
    style: styles.modalRow
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.deleteText
  }, isReportByMe ? 'Undo Report' : 'Report'))))), /*#__PURE__*/React.createElement(EditCommentModal, {
    visible: editCommentModal,
    commentDetail: commentDetail,
    onFinishEdit: onEditComment,
    onClose: onCloseEditCommentModal
  }));
};
export default CommentList;
//# sourceMappingURL=index.js.map