import { memo, useEffect, useRef, useState } from 'react';
import { View, Text, TouchableOpacity, Image, Modal, Animated, Alert, FlatList } from 'react-native';
import { useStyles } from './styles';
import { SvgXml } from 'react-native-svg';
import { editIcon, expandIcon, likeCircle, personXml, reportOutLine, storyDraftDeletHyperLink, 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 '../../../../../components/legacy/EditCommentModal';
import { useTheme } from 'react-native-paper';
import ReplyCommentList from '../ReplyCommentList/index';
import { CommentRepository } from '@amityco/ts-sdk-react-native';
import { useTimeDifference } from '../../../../../hooks';
import ModeratorBadgeElement from '../../../../../elements/ModeratorBadgeElement/ModeratorBadgeElement';
import { BrandBadge } from '../../../../../elements/BrandBadge';
import { ComponentID, PageID } from '../../../../../enums';
import { LinkPreview } from '../../../../../components/PreviewLink/LinkPreview';
import AmityReactionListComponent from '../../../../reaction/components/List';
import uiSlice from '../../../../../../core/stores/slices/uiSlice';
import { useUIKitDispatch } from '../../../../../../core/stores/store';
import { useNavigation } from '@react-navigation/native';
const CommentListItem = ({
  commentDetail,
  onDelete,
  onClickReply,
  postType,
  disabledInteraction,
  onNavigate
}) => {
  var _previewReplyCommentL;
  const theme = useTheme();
  const styles = useStyles();
  const {
    commentId,
    data,
    user,
    createdAt,
    reactions,
    myReactions,
    childrenComment,
    editedAt,
    mentionPosition,
    referenceId,
    targetType,
    targetId,
    childrenNumber
  } = commentDetail ?? {};
  const timeDifference = useTimeDifference(createdAt);
  const dispatch = useUIKitDispatch();
  const {
    showToastMessage
  } = uiSlice.actions;
  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 [isReactionListVisible, setIsReactionListVisible] = useState(false);
  const navigation = useNavigation();
  useEffect(() => {
    getReplyComments();
    setIsOpenReply(false);
    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 _userObject$data, _userObject$data2, _item$metadata;
        const {
          userObject
        } = await getAmityUser(item.userId);
        let formattedUserObject;
        formattedUserObject = {
          userId: userObject.data.userId,
          displayName: userObject.data.displayName,
          avatarFileId: userObject.data.avatarFileId,
          avatarCustomUrl: (_userObject$data = userObject.data) === null || _userObject$data === void 0 ? void 0 : _userObject$data.avatarCustomUrl,
          isBrand: (_userObject$data2 = userObject.data) === null || _userObject$data2 === void 0 ? void 0 : _userObject$data2.isBrand
        };
        return {
          targetType: item.targetType,
          targetId: item.targetId,
          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: postType,
      referenceId: referenceId,
      // post ID
      dataTypes: {
        values: ['text', 'image'],
        matchType: 'any'
      },
      limit: 5,
      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 deleteComment = () => {
    Alert.alert('Delete comment', 'This comment will be permanently deleted.', [{
      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);
      setIsVisible(false);
      setIsReportByMe(false);
      if (unReportPost) {
        dispatch(showToastMessage({
          toastMessage: 'Comment unreported',
          isSuccessToast: true
        }));
      }
    } else {
      const reportPost = await reportTargetById('comment', commentId);
      setIsVisible(false);
      setIsReportByMe(true);
      if (reportPost) {
        dispatch(showToastMessage({
          toastMessage: 'Comment reported',
          isSuccessToast: true
        }));
      }
    }
  };
  const modalStyle = {
    transform: [{
      translateY: slideAnimation.interpolate({
        inputRange: [0, 1],
        outputRange: [580, 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 = () => {
    onNavigate && onNavigate();
    setIsReactionListVisible(true);
  };
  const replyCount = childrenNumber === 0 ? replyCommentList.length : childrenNumber;
  return /*#__PURE__*/React.createElement(View, {
    key: commentId,
    style: styles.commentWrap
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.headerSection
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => {
      (user === null || user === void 0 ? void 0 : user.userId) && navigation.navigate('UserProfile', {
        userId: (user === null || user === void 0 ? void 0 : user.userId) || ''
      });
    }
  }, user !== null && user !== void 0 && user.avatarFileId ? /*#__PURE__*/React.createElement(Image, {
    style: styles.avatar,
    source: {
      uri: user !== null && user !== void 0 && user.avatarCustomUrl ? user === null || user === void 0 ? void 0 : user.avatarCustomUrl : `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.commentBubble
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => {
      (user === null || user === void 0 ? void 0 : user.userId) && navigation.navigate('UserProfile', {
        userId: (user === null || user === void 0 ? void 0 : user.userId) || ''
      });
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.displayNameRow
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerText,
    numberOfLines: 1,
    ellipsizeMode: "tail"
  }, user === null || user === void 0 ? void 0 : user.displayName), (user === null || user === void 0 ? void 0 : user.isBrand) && /*#__PURE__*/React.createElement(BrandBadge, {
    width: 16,
    height: 16
  }))), targetType === 'community' && targetId &&
  /*#__PURE__*/
  // eslint-disable-next-line react-native/no-inline-styles
  React.createElement(View, {
    style: {
      marginVertical: 6
    }
  }, /*#__PURE__*/React.createElement(ModeratorBadgeElement, {
    pageID: PageID.WildCardPage,
    communityId: targetId,
    userId: user === null || user === void 0 ? void 0 : user.userId,
    componentID: ComponentID.post_content
  })), textComment && /*#__PURE__*/React.createElement(LinkPreview, {
    mentionPositionArr: mentionPosition,
    text: textComment
  })), !disabledInteraction && /*#__PURE__*/React.createElement(View, {
    style: styles.actionSection
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.rowContainer
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.timeRow
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerTextTime
  }, timeDifference), (editedAt !== createdAt || isEditComment) && /*#__PURE__*/React.createElement(Text, {
    style: styles.headerTextTime
  }, " (edited)")), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => addReactionToComment(),
    style: styles.likeBtn
  }, /*#__PURE__*/React.createElement(Text, {
    style: isLike ? styles.likedText : styles.btnText
  }, !isLike ? 'Like' : 'Liked')), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: onHandleReply,
    style: styles.likeBtn
  }, /*#__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"
  }))), likeReaction > 0 && /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: onPressCommentReaction,
    style: styles.likeBtn
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.btnText
  }, likeReaction), /*#__PURE__*/React.createElement(SvgXml
  // eslint-disable-next-line react-native/no-inline-styles
  , {
    style: {
      marginLeft: 4
    },
    xml: likeCircle,
    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 && (replyCommentList === null || replyCommentList === void 0 ? void 0 : replyCommentList.length) > 0 && /*#__PURE__*/React.createElement(FlatList, {
    data: replyCommentList,
    renderItem: ({
      item
    }) => /*#__PURE__*/React.createElement(ReplyCommentList, {
      commentId: item.commentId,
      commentDetail: item,
      onDelete: onDelete
    }),
    keyExtractor: item => item.commentId
  }), (replyCommentList === null || replyCommentList === void 0 ? void 0 : replyCommentList.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 ", replyCount, " ", replyCount === 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]
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.handleBar
  }), (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(SvgXml, {
    xml: editIcon(theme.colors.base),
    width: "20",
    height: "20"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.deleteText
  }, " Edit Comment")), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: deleteComment,
    style: styles.modalRow
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: storyDraftDeletHyperLink(),
    width: "20",
    height: "20"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.deleteText
  }, " Delete Comment"))) : /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: reportCommentObject,
    style: styles.modalRow
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: reportOutLine(theme.colors.base),
    width: "20",
    height: "20"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.deleteText
  }, isReportByMe ? 'Unreport comment' : 'Report comment'))))), /*#__PURE__*/React.createElement(EditCommentModal, {
    visible: editCommentModal,
    commentDetail: commentDetail,
    onFinishEdit: onEditComment,
    onClose: onCloseEditCommentModal
  }), isReactionListVisible && /*#__PURE__*/React.createElement(AmityReactionListComponent, {
    referenceId: commentId,
    referenceType: "comment",
    isModalVisible: isReactionListVisible,
    onCloseModal: () => setIsReactionListVisible(false)
  }));
};
export default /*#__PURE__*/memo(CommentListItem);
//# sourceMappingURL=CommentListItem.js.map