import { useCallback, useEffect, useRef, useState } from 'react';
import { View, Text, TouchableOpacity, Image, Modal, Pressable, Animated, Alert } from 'react-native';
import { SvgXml } from 'react-native-svg';
import { arrowXml, commentXml, likedXml, likeXml, personXml, threeDots } from '../../../../../core/assets/icons/xml';
import { useStyles } from './styles';
import { addPostReaction, isReportTarget, removePostReaction, reportTargetById, unReportTargetById } from '../../../../../core/legacy/feed';
import { useNavigation } from '@react-navigation/native';
import useAuth from '../../../../../core/hooks/useAuth';
import EditPostModal from '../../EditPostModal';
import { useTheme } from 'react-native-paper';
import postDetailSlice from '../../../../../core/stores/slices/postDetailSlice';
import globalFeedSlice from '../../../../../core/stores/slices/globalfeedSlice';
import feedSlice from '../../../../../core/stores/slices/feedSlice';
import { useTimeDifference } from '../../../../../core/hooks/useTimeDifference';
import { CommunityRepository } from '@amityco/ts-sdk-react-native';
import PostContent from '../../../PostContent';
import { useUIKitDispatch } from '../../../../../core/stores/store';
export default function PostList({
  postDetail,
  onDelete
}) {
  const theme = useTheme();
  const {
    client,
    apiRegion
  } = useAuth();
  const styles = useStyles();
  const [isLike, setIsLike] = useState(false);
  const [likeReaction, setLikeReaction] = useState(0);
  const [communityName, setCommunityName] = useState('');
  const [isJoined, setIsJoined] = useState(true);
  const [textPost, setTextPost] = useState('');
  const [privateCommunityId, setPrivateCommunityId] = useState(null);
  const [isVisible, setIsVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [isReportByMe, setIsReportByMe] = useState(false);
  const [editPostModalVisible, setEditPostModalVisible] = useState(false);
  const slideAnimation = useRef(new Animated.Value(0)).current;
  const navigation = useNavigation();
  const dispatch = useUIKitDispatch();
  const [mentionPositionArr, setMentionsPositionArr] = useState([]);
  const {
    updateByPostId: updateByPostIdGlobalFeed
  } = globalFeedSlice.actions;
  const {
    updateByPostId
  } = feedSlice.actions;
  const {
    updatePostDetail
  } = postDetailSlice.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 = useTimeDifference(createdAt);
  useEffect(() => {
    if (mentionPosition) {
      setMentionsPositionArr(mentionPosition);
    }
  }, [mentionPosition]);
  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 = () => {
    Animated.timing(slideAnimation, {
      toValue: 0,
      duration: 100,
      useNativeDriver: true
    }).start(() => setIsVisible(false));
  };
  const checkIsReport = useCallback(async () => {
    const isReport = await isReportTarget('post', postId);
    if (isReport) {
      setIsReportByMe(true);
    }
  }, [postId]);
  useEffect(() => {
    checkIsReport();
  }, [checkIsReport]);
  useEffect(() => {
    let unsubCommunity;
    if (targetType === 'community' && targetId) {
      unsubCommunity = 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]);
  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 = useCallback(likeNumber => {
    if (!likeNumber) return '';
    if (likeNumber === 1) return 'like';
    return 'likes';
  }, []);
  const renderCommentText = useCallback(commentNumber => {
    if (!commentNumber) return '';
    if (commentNumber === 1) return 'comment';
    return 'comments';
  }, []);
  const addReactionToPost = 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 removePostReaction(postId, 'like');
      } else {
        await 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 = () => {
    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 unReportTargetById('post', postId);
      if (unReportPost) {
        Alert.alert('Undo Report sent');
      }
      setIsVisible(false);
      setIsReportByMe(false);
    } else {
      const reportPost = await reportTargetById('post', postId);
      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 renderOptionModal = () => {
    return /*#__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: openEditPostModal,
      style: styles.modalRow
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.deleteText
    }, " Edit Post")), /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: deletePostObject,
      style: styles.modalRow
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.deleteText
    }, " Delete Post"))) : /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: reportPostObject,
      style: styles.modalRow
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.deleteText
    }, isReportByMe ? 'Undo Report' : 'Report')))));
  };
  const closeEditPostModal = () => {
    setEditPostModalVisible(false);
  };
  const openEditPostModal = () => {
    setIsVisible(false);
    setEditPostModalVisible(true);
  };
  const handleOnFinishEdit = useCallback(postData => {
    setTextPost(postData.text);
    setEditPostModalVisible(false);
    setIsEdit(true);
  }, []);
  const onClickReactions = useCallback(() => {
    navigation.navigate('ReactionList', {
      referenceId: postId,
      referenceType: 'post'
    });
  }, [navigation, postId]);
  const onPressPost = () => {
    navigation.navigate('PostDetail', {
      postId: postDetail.postId
    });
  };
  return /*#__PURE__*/React.createElement(View, {
    key: postId,
    style: styles.postWrap
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.headerSection
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.user
  }, user !== null && user !== void 0 && user.userId ? /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: handleDisplayNamePress
  }, user !== null && user !== void 0 && user.avatarCustomUrl ? /*#__PURE__*/React.createElement(Image, {
    style: styles.avatar,
    source: {
      uri: user.avatarCustomUrl
    }
  }) : 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.avatarFileId}/download`
    }
  }) : /*#__PURE__*/React.createElement(View, {
    style: styles.avatar
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: personXml,
    width: "20",
    height: "16"
  }))) : /*#__PURE__*/React.createElement(React.Fragment, null, user !== null && user !== void 0 && user.avatarCustomUrl ? /*#__PURE__*/React.createElement(Image, {
    style: styles.avatar,
    source: {
      uri: user.avatarCustomUrl
    }
  }) : 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.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.fillSpace
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.headerRow
  }, user !== null && user !== void 0 && user.userId ? /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: handleDisplayNamePress
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerText
  }, user === null || user === void 0 ? void 0 : user.displayName)) : /*#__PURE__*/React.createElement(Text, {
    style: styles.headerText
  }, user === null || user === void 0 ? void 0 : user.displayName), communityName && /*#__PURE__*/React.createElement(View, {
    style: styles.communityNameContainer
  }, /*#__PURE__*/React.createElement(SvgXml, {
    style: styles.arrow,
    xml: arrowXml,
    width: "8",
    height: "8"
  }), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: handleCommunityNamePress
  }, /*#__PURE__*/React.createElement(Text, {
    ellipsizeMode: "tail",
    numberOfLines: 3,
    style: styles.headerText
  }, communityName)))), /*#__PURE__*/React.createElement(View, {
    style: styles.timeRow
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerTextTime
  }, timeDifference), (editedAt !== createdAt || isEdit) && /*#__PURE__*/React.createElement(Text, {
    style: styles.dot
  }, "\xB7"), (editedAt !== createdAt || isEdit) && /*#__PURE__*/React.createElement(Text, {
    style: styles.headerTextTime
  }, "Edited")))), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: openModal,
    style: styles.threeDots
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: threeDots(theme.colors.base),
    width: "20",
    height: "16"
  }))), /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(View, {
    style: styles.bodySection
  }, /*#__PURE__*/React.createElement(PostContent, {
    post: postDetail,
    childrenPosts: childrenPosts,
    textPost: textPost,
    onPressPost: onPressPost,
    mentionPositionArr: mentionPositionArr
  })), likeReaction === 0 && commentsCount === 0 ? '' : /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(View, {
    style: styles.countSection
  }, likeReaction ? /*#__PURE__*/React.createElement(Text, {
    style: styles.likeCountText,
    onPress: onClickReactions
  }, likeReaction, " ", renderLikeText(likeReaction)) : /*#__PURE__*/React.createElement(Text, null), commentsCount > 0 && /*#__PURE__*/React.createElement(Text, {
    style: styles.commentCountText
  }, commentsCount > 0 && commentsCount, ' ', renderCommentText(commentsCount)))), targetType !== 'community' || isJoined !== false ? /*#__PURE__*/React.createElement(View, {
    style: styles.actionSection
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => addReactionToPost(isLike),
    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
  }, "Like")), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: onClickComment,
    style: styles.commentBtn
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: commentXml,
    width: "20",
    height: "16"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.btnText
  }, "Comment"))) : /*#__PURE__*/React.createElement(View, {
    style: styles.actionSection
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.btnText
  }, "Join community to interact with all posts"))), renderOptionModal(), editPostModalVisible && /*#__PURE__*/React.createElement(EditPostModal, {
    privateCommunityId: privateCommunityId,
    visible: editPostModalVisible,
    onClose: closeEditPostModal,
    postDetail: {
      ...postDetail,
      data: {
        ...(typeof data === 'object' && data !== null ? data : {}),
        text: textPost
      }
    },
    onFinishEdit: handleOnFinishEdit
  }));
}
//# sourceMappingURL=index.js.map