"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = PostList;
var _react = require("react");
var _reactNative = require("react-native");
var _reactNativeSvg = require("react-native-svg");
var _xml = require("../../../../../core/assets/icons/xml");
var _styles = require("./styles");
var _feed = require("../../../../../core/legacy/feed");
var _native = require("@react-navigation/native");
var _useAuth = _interopRequireDefault(require("../../../../../core/hooks/useAuth"));
var _EditPostModal = _interopRequireDefault(require("../../EditPostModal"));
var _reactNativePaper = require("react-native-paper");
var _postDetailSlice = _interopRequireDefault(require("../../../../../core/stores/slices/postDetailSlice"));
var _globalfeedSlice = _interopRequireDefault(require("../../../../../core/stores/slices/globalfeedSlice"));
var _feedSlice = _interopRequireDefault(require("../../../../../core/stores/slices/feedSlice"));
var _useTimeDifference = require("../../../../../core/hooks/useTimeDifference");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _PostContent = _interopRequireDefault(require("../../../PostContent"));
var _store = require("../../../../../core/stores/store");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function PostList({
  postDetail,
  onDelete
}) {
  const theme = (0, _reactNativePaper.useTheme)();
  const {
    client,
    apiRegion
  } = (0, _useAuth.default)();
  const styles = (0, _styles.useStyles)();
  const [isLike, setIsLike] = (0, _react.useState)(false);
  const [likeReaction, setLikeReaction] = (0, _react.useState)(0);
  const [communityName, setCommunityName] = (0, _react.useState)('');
  const [isJoined, setIsJoined] = (0, _react.useState)(true);
  const [textPost, setTextPost] = (0, _react.useState)('');
  const [privateCommunityId, setPrivateCommunityId] = (0, _react.useState)(null);
  const [isVisible, setIsVisible] = (0, _react.useState)(false);
  const [isEdit, setIsEdit] = (0, _react.useState)(false);
  const [isReportByMe, setIsReportByMe] = (0, _react.useState)(false);
  const [editPostModalVisible, setEditPostModalVisible] = (0, _react.useState)(false);
  const slideAnimation = (0, _react.useRef)(new _reactNative.Animated.Value(0)).current;
  const navigation = (0, _native.useNavigation)();
  const dispatch = (0, _store.useUIKitDispatch)();
  const [mentionPositionArr, setMentionsPositionArr] = (0, _react.useState)([]);
  const {
    updateByPostId: updateByPostIdGlobalFeed
  } = _globalfeedSlice.default.actions;
  const {
    updateByPostId
  } = _feedSlice.default.actions;
  const {
    updatePostDetail
  } = _postDetailSlice.default.actions;
  const {
    postId,
    data,
    myReactions = [],
    reactions: reactionCount,
    commentsCount,
    createdAt,
    creator: user,
    targetType,
    targetId,
    children: childrenPosts = [],
    editedAt,
    metadata
  } = postDetail ?? {};
  const mentionPosition = metadata === null || metadata === void 0 ? void 0 : metadata.mentioned;
  const timeDifference = (0, _useTimeDifference.useTimeDifference)(createdAt);
  (0, _react.useEffect)(() => {
    if (mentionPosition) {
      setMentionsPositionArr(mentionPosition);
    }
  }, [mentionPosition]);
  (0, _react.useEffect)(() => {
    if (myReactions && (myReactions === null || myReactions === void 0 ? void 0 : myReactions.length) > 0) {
      setIsLike(true);
    } else {
      setIsLike(false);
    }
    if (reactionCount !== null && reactionCount !== void 0 && reactionCount.like) {
      setLikeReaction(reactionCount === null || reactionCount === void 0 ? void 0 : reactionCount.like);
    } else {
      setLikeReaction(0);
    }
  }, [myReactions, reactionCount]);
  const openModal = () => {
    setIsVisible(true);
  };
  const closeModal = () => {
    _reactNative.Animated.timing(slideAnimation, {
      toValue: 0,
      duration: 100,
      useNativeDriver: true
    }).start(() => setIsVisible(false));
  };
  const checkIsReport = (0, _react.useCallback)(async () => {
    const isReport = await (0, _feed.isReportTarget)('post', postId);
    if (isReport) {
      setIsReportByMe(true);
    }
  }, [postId]);
  (0, _react.useEffect)(() => {
    checkIsReport();
  }, [checkIsReport]);
  (0, _react.useEffect)(() => {
    let unsubCommunity;
    if (targetType === 'community' && targetId) {
      unsubCommunity = _tsSdkReactNative.CommunityRepository.getCommunity(targetId, ({
        error,
        loading,
        data: community
      }) => {
        if (error) return;
        if (!loading) {
          setCommunityName(community.displayName);
          setIsJoined(community.isJoined);
          !community.isPublic && setPrivateCommunityId(community.communityId);
        }
      });
    }
    return () => unsubCommunity && unsubCommunity();
  }, [targetId, targetType]);
  (0, _react.useEffect)(() => {
    setTextPost(data === null || data === void 0 ? void 0 : data.text);
    if (myReactions.length > 0 && myReactions.includes('like')) {
      setIsLike(true);
    }
    if (reactionCount !== null && reactionCount !== void 0 && reactionCount.like) {
      setLikeReaction(reactionCount === null || reactionCount === void 0 ? void 0 : reactionCount.like);
    }
  }, [data, myReactions, reactionCount === null || reactionCount === void 0 ? void 0 : reactionCount.like, targetId, targetType]);
  const renderLikeText = (0, _react.useCallback)(likeNumber => {
    if (!likeNumber) return '';
    if (likeNumber === 1) return 'like';
    return 'likes';
  }, []);
  const renderCommentText = (0, _react.useCallback)(commentNumber => {
    if (!commentNumber) return '';
    if (commentNumber === 1) return 'comment';
    return 'comments';
  }, []);
  const addReactionToPost = (0, _react.useCallback)(async isLiked => {
    setIsLike(prev => !prev);
    setLikeReaction(prev => isLiked ? prev - 1 : prev + 1);
    const updatedLikeReaction = isLiked ? likeReaction - 1 : likeReaction + 1;
    const updatedPost = {
      ...postDetail,
      reactionCount: {
        like: updatedLikeReaction
      },
      myReactions: isLiked ? [] : ['like']
    };
    try {
      dispatch(updateByPostIdGlobalFeed({
        postId: postId,
        postDetail: updatedPost
      }));
      dispatch(updateByPostId({
        postId: postId,
        postDetail: updatedPost
      }));
      if (isLiked) {
        await (0, _feed.removePostReaction)(postId, 'like');
      } else {
        await (0, _feed.addPostReaction)(postId, 'like');
      }
    } catch (error) {
      setLikeReaction(prev => prev);
    }
  }, [dispatch, likeReaction, postDetail, postId, updateByPostId, updateByPostIdGlobalFeed]);
  function onClickComment() {
    dispatch(updatePostDetail({
      ...postDetail,
      myReactions: isLike ? ['like'] : [],
      reactions: {
        like: likeReaction
      },
      commentsCount: commentsCount
    }));
    navigation.navigate('PostDetail', {
      postId: postDetail.postId
    });
  }
  const handleDisplayNamePress = () => {
    if (user !== null && user !== void 0 && user.userId) {
      navigation.navigate('UserProfile', {
        userId: user.userId
      });
    }
  };
  const handleCommunityNamePress = () => {
    if (targetType === 'community' && targetId) {
      navigation.navigate('CommunityHome', {
        communityId: targetId,
        communityName: communityName
      });
    }
  };
  const deletePostObject = () => {
    _reactNative.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(postId)
    }]);
    setIsVisible(false);
  };
  const reportPostObject = async () => {
    if (isReportByMe) {
      const unReportPost = await (0, _feed.unReportTargetById)('post', postId);
      if (unReportPost) {
        _reactNative.Alert.alert('Undo Report sent');
      }
      setIsVisible(false);
      setIsReportByMe(false);
    } else {
      const reportPost = await (0, _feed.reportTargetById)('post', postId);
      if (reportPost) {
        _reactNative.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 renderOptionModal = () => {
    return /*#__PURE__*/React.createElement(_reactNative.Modal, {
      animationType: "fade",
      transparent: true,
      visible: isVisible,
      onRequestClose: closeModal
    }, /*#__PURE__*/React.createElement(_reactNative.Pressable, {
      onPress: closeModal,
      style: styles.modalContainer
    }, /*#__PURE__*/React.createElement(_reactNative.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(_reactNative.View, null, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      onPress: openEditPostModal,
      style: styles.modalRow
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.deleteText
    }, " Edit Post")), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      onPress: deletePostObject,
      style: styles.modalRow
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.deleteText
    }, " Delete Post"))) : /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
      onPress: reportPostObject,
      style: styles.modalRow
    }, /*#__PURE__*/React.createElement(_reactNative.Text, {
      style: styles.deleteText
    }, isReportByMe ? 'Undo Report' : 'Report')))));
  };
  const closeEditPostModal = () => {
    setEditPostModalVisible(false);
  };
  const openEditPostModal = () => {
    setIsVisible(false);
    setEditPostModalVisible(true);
  };
  const handleOnFinishEdit = (0, _react.useCallback)(postData => {
    setTextPost(postData.text);
    setEditPostModalVisible(false);
    setIsEdit(true);
  }, []);
  const onClickReactions = (0, _react.useCallback)(() => {
    navigation.navigate('ReactionList', {
      referenceId: postId,
      referenceType: 'post'
    });
  }, [navigation, postId]);
  const onPressPost = () => {
    navigation.navigate('PostDetail', {
      postId: postDetail.postId
    });
  };
  return /*#__PURE__*/React.createElement(_reactNative.View, {
    key: postId,
    style: styles.postWrap
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.headerSection
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.user
  }, user !== null && user !== void 0 && user.userId ? /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: handleDisplayNamePress
  }, user !== null && user !== void 0 && user.avatarCustomUrl ? /*#__PURE__*/React.createElement(_reactNative.Image, {
    style: styles.avatar,
    source: {
      uri: user.avatarCustomUrl
    }
  }) : user !== null && user !== void 0 && user.avatarFileId ? /*#__PURE__*/React.createElement(_reactNative.Image, {
    style: styles.avatar,
    source: {
      uri: `https://api.${apiRegion}.amity.co/api/v3/files/${user.avatarFileId}/download`
    }
  }) : /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.avatar
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: _xml.personXml,
    width: "20",
    height: "16"
  }))) : /*#__PURE__*/React.createElement(React.Fragment, null, user !== null && user !== void 0 && user.avatarCustomUrl ? /*#__PURE__*/React.createElement(_reactNative.Image, {
    style: styles.avatar,
    source: {
      uri: user.avatarCustomUrl
    }
  }) : user !== null && user !== void 0 && user.avatarFileId ? /*#__PURE__*/React.createElement(_reactNative.Image, {
    style: styles.avatar,
    source: {
      uri: `https://api.${apiRegion}.amity.co/api/v3/files/${user.avatarFileId}/download`
    }
  }) : /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.avatar
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: _xml.personXml,
    width: "20",
    height: "16"
  }))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.fillSpace
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.headerRow
  }, user !== null && user !== void 0 && user.userId ? /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: handleDisplayNamePress
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.headerText
  }, user === null || user === void 0 ? void 0 : user.displayName)) : /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.headerText
  }, user === null || user === void 0 ? void 0 : user.displayName), communityName && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.communityNameContainer
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    style: styles.arrow,
    xml: _xml.arrowXml,
    width: "8",
    height: "8"
  }), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: handleCommunityNamePress
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    ellipsizeMode: "tail",
    numberOfLines: 3,
    style: styles.headerText
  }, communityName)))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.timeRow
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.headerTextTime
  }, timeDifference), (editedAt !== createdAt || isEdit) && /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.dot
  }, "\xB7"), (editedAt !== createdAt || isEdit) && /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.headerTextTime
  }, "Edited")))), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: openModal,
    style: styles.threeDots
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.threeDots)(theme.colors.base),
    width: "20",
    height: "16"
  }))), /*#__PURE__*/React.createElement(_reactNative.View, null, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.bodySection
  }, /*#__PURE__*/React.createElement(_PostContent.default, {
    post: postDetail,
    childrenPosts: childrenPosts,
    textPost: textPost,
    onPressPost: onPressPost,
    mentionPositionArr: mentionPositionArr
  })), likeReaction === 0 && commentsCount === 0 ? '' : /*#__PURE__*/React.createElement(_reactNative.View, null, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.countSection
  }, likeReaction ? /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.likeCountText,
    onPress: onClickReactions
  }, likeReaction, " ", renderLikeText(likeReaction)) : /*#__PURE__*/React.createElement(_reactNative.Text, null), commentsCount > 0 && /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.commentCountText
  }, commentsCount > 0 && commentsCount, ' ', renderCommentText(commentsCount)))), targetType !== 'community' || isJoined !== false ? /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.actionSection
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: () => addReactionToPost(isLike),
    style: styles.likeBtn
  }, isLike ? /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.likedXml)(theme.colors.primary),
    width: "20",
    height: "16"
  }) : /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: _xml.likeXml,
    width: "20",
    height: "16"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: isLike ? styles.likedText : styles.btnText
  }, "Like")), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: onClickComment,
    style: styles.commentBtn
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: _xml.commentXml,
    width: "20",
    height: "16"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.btnText
  }, "Comment"))) : /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.actionSection
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.btnText
  }, "Join community to interact with all posts"))), renderOptionModal(), editPostModalVisible && /*#__PURE__*/React.createElement(_EditPostModal.default, {
    privateCommunityId: privateCommunityId,
    visible: editPostModalVisible,
    onClose: closeEditPostModal,
    postDetail: {
      ...postDetail,
      data: {
        ...(typeof data === 'object' && data !== null ? data : {}),
        text: textPost
      }
    },
    onFinishEdit: handleOnFinishEdit
  }));
}
//# sourceMappingURL=index.js.map