import { Fragment, memo, useCallback, useEffect, useState } from 'react';
import { Image, Pressable, Text, TouchableOpacity, TouchableWithoutFeedback, View } from 'react-native';
import { SvgXml } from 'react-native-svg';
import { useStyles } from './styles';
import useAuth from '../../../core/hooks/useAuth';
import { getPostById } from '../../../core/legacy/feed';
import ImageView from '../legacy/react-native-image-viewing/dist';
import { useUIKitSelector } from '../../../core/stores/store';
import { playBtn } from '../../../core/assets/icons/xml';
import LivestreamContent from '../LivestreamContent';
import { LinkPreview } from '../PreviewLink';
import RenderTextWithMention from '../RenderTextWithMention/RenderTextWithMention';
import PollContent from '../PollContent';
const PostContent = ({
  post,
  textPost,
  onPressPost,
  disabledPoll,
  childrenPosts,
  showedAllOptions,
  mentionPositionArr
}) => {
  const {
    apiRegion
  } = useAuth();
  const [imagePosts, setImagePosts] = useState([]);
  const [videoPosts, setVideoPosts] = useState([]);
  const [pollIds, setPollIds] = useState([]);
  const [livestreamId, setLivestreamId] = useState([]);
  const [imagePostsFullSize, setImagePostsFullSize] = useState([]);
  const [videoPostsFullSize, setVideoPostsFullSize] = useState([]);
  const [visibleFullImage, setIsVisibleFullImage] = useState(false);
  const [imageIndex, setImageIndex] = useState(0);
  const styles = useStyles();
  let imageStyle = styles.imageLargePost;
  let colStyle = styles.col2;
  const {
    currentPostdetail
  } = useUIKitSelector(state => state.postDetail);
  const {
    postList: postListGlobal
  } = useUIKitSelector(state => state.globalFeed);
  const {
    postList
  } = useUIKitSelector(state => state.feed);
  useEffect(() => {
    setImagePostsFullSize([]);
    setVideoPostsFullSize([]);
    if (imagePosts.length > 0) {
      const updatedUrls = imagePosts.map(url => {
        return {
          uri: url.replace('size=medium', 'size=large')
        };
      });
      setImagePostsFullSize(updatedUrls);
    }
    if (videoPosts.length > 0) {
      const updatedUrls = videoPosts.map(item => {
        return {
          uri: `https://api.${apiRegion}.amity.co/api/v3/files/${item === null || item === void 0 ? void 0 : item.thumbnailFileId}/download?size=large`
        };
      });
      setVideoPostsFullSize(updatedUrls);
    }
  }, [imagePosts, videoPosts, apiRegion]);
  const getPostInfo = useCallback(async () => {
    try {
      const response = await Promise.all(childrenPosts.map(async id => {
        const {
          data: childrenPost
        } = await getPostById(id);
        return {
          dataType: childrenPost === null || childrenPost === void 0 ? void 0 : childrenPost.dataType,
          data: childrenPost === null || childrenPost === void 0 ? void 0 : childrenPost.data
        };
      }));
      const images = [];
      const videos = [];
      const polls = [];
      const livestreams = [];
      response.forEach(item => {
        var _item$data, _item$data2;
        if ((item === null || item === void 0 ? void 0 : item.dataType) === 'image' && item !== null && item !== void 0 && (_item$data = item.data) !== null && _item$data !== void 0 && _item$data.fileId) {
          const url = `https://api.${apiRegion}.amity.co/api/v3/files/${item === null || item === void 0 ? void 0 : item.data.fileId}/download?size=medium`;
          if (!images.includes(url)) {
            images.push(url);
          }
        } else if ((item === null || item === void 0 ? void 0 : item.dataType) === 'video' && item !== null && item !== void 0 && (_item$data2 = item.data) !== null && _item$data2 !== void 0 && _item$data2.videoFileId.original) {
          const isExisted = videos.some(video => video.videoFileId.original === item.data.videoFileId.original);
          if (!isExisted) {
            videos.push(item.data);
          }
        } else if ((item === null || item === void 0 ? void 0 : item.dataType) === 'poll') {
          if (!polls.some(poll => poll.pollId === item.data.pollId)) {
            polls.push(item.data);
          }
        } else if ((item === null || item === void 0 ? void 0 : item.dataType) === 'room') {
          if (!livestreams.includes(item.data.roomId)) {
            livestreams.push(item.data.roomId);
          }
        }
      });
      if (images.length > 0) {
        setImagePosts(images);
      }
      if (videos.length > 0) {
        setVideoPosts(videos);
      }
      if (polls.length > 0) {
        setPollIds(polls);
      }
      if (livestreams.length > 0) {
        setLivestreamId(livestreams);
      }
    } catch (error) {
      console.log('error: ', error);
    }
  }, [apiRegion, childrenPosts]);
  useEffect(() => {
    setVideoPosts([]);
    setImagePosts([]);
    getPostInfo();
  }, [childrenPosts, currentPostdetail, postList, postListGlobal, getPostInfo]);
  function onClickImage(index) {
    setIsVisibleFullImage(true);
    setImageIndex(index);
  }
  function renderMediaPosts() {
    const thumbnailFileIds = videoPosts.length > 0 ? videoPosts.map(item => {
      return `https://api.${apiRegion}.amity.co/api/v3/files/${item === null || item === void 0 ? void 0 : item.thumbnailFileId}/download?size=medium`;
    }) : [];
    const mediaPosts = [...imagePosts].length > 0 ? [...imagePosts] : [...thumbnailFileIds];
    const imageElement = mediaPosts.map((item, index) => {
      if (mediaPosts.length === 1) {
        imageStyle = styles.imageLargePost;
        colStyle = styles.col6;
      } else if (mediaPosts.length === 2) {
        colStyle = styles.col3;
        if (index === 0) {
          imageStyle = [styles.imageLargePost, styles.imageMarginRight];
        } else {
          imageStyle = [styles.imageLargePost, styles.imageMarginLeft];
        }
      } else if (mediaPosts.length === 3) {
        switch (index) {
          case 0:
            colStyle = styles.col6;
            imageStyle = [styles.imageMediumPost, styles.imageMarginBottom];
            break;
          case 1:
            colStyle = styles.col3;
            imageStyle = [styles.imageMediumPost, styles.imageMarginTop, styles.imageMarginRight];
            break;
          case 2:
            colStyle = styles.col3;
            imageStyle = [styles.imageMediumPost, styles.imageMarginTop, styles.imageMarginLeft];
            break;
          default:
            break;
        }
      } else {
        switch (index) {
          case 0:
            colStyle = styles.col6;
            imageStyle = [styles.imageMediumLargePost, styles.imageMarginBottom];
            break;
          case 1:
            colStyle = styles.col2;
            imageStyle = [styles.imageSmallPost, styles.imageMarginTop, styles.imageMarginRight];
            break;
          case 2:
            colStyle = styles.col2;
            imageStyle = [styles.imageSmallPost, styles.imageMarginTop, styles.imageMarginLeft, styles.imageMarginRight];
            break;
          case 3:
            colStyle = styles.col2;
            imageStyle = [styles.imageSmallPost, styles.imageMarginTop, styles.imageMarginLeft];
            break;
          default:
            break;
        }
      }
      return /*#__PURE__*/React.createElement(View, {
        style: colStyle,
        key: item
      }, /*#__PURE__*/React.createElement(TouchableWithoutFeedback, {
        onPress: () => onClickImage(index)
      }, /*#__PURE__*/React.createElement(View, null, videoPosts.length > 0 && renderPlayButton(), /*#__PURE__*/React.createElement(Image, {
        style: imageStyle,
        source: {
          uri: item
        }
      }), index === 3 && imagePosts.length > 4 && /*#__PURE__*/React.createElement(View, {
        style: styles.overlay
      }, /*#__PURE__*/React.createElement(Text, {
        style: styles.overlayText
      }, `+ ${imagePosts.length - 3}`)))));
    });
    if (imageElement.length < 3) {
      return /*#__PURE__*/React.createElement(View, {
        style: styles.imagesWrap
      }, /*#__PURE__*/React.createElement(View, {
        style: styles.row
      }, imageElement));
    } else if (imageElement.length === 3) {
      return /*#__PURE__*/React.createElement(View, {
        style: [styles.imagesWrap]
      }, /*#__PURE__*/React.createElement(View, {
        style: styles.row
      }, imageElement.slice(0, 1)), /*#__PURE__*/React.createElement(View, {
        style: styles.row
      }, imageElement.slice(1, 3)));
    } else {
      return /*#__PURE__*/React.createElement(View, {
        style: styles.imagesWrap
      }, /*#__PURE__*/React.createElement(View, {
        style: styles.row
      }, imageElement.slice(0, 1)), /*#__PURE__*/React.createElement(View, {
        style: styles.row
      }, imageElement.slice(1, 4)));
    }
  }
  function renderPlayButton() {
    return /*#__PURE__*/React.createElement(View, {
      style: styles.playButton
    }, /*#__PURE__*/React.createElement(SvgXml, {
      xml: playBtn,
      width: "50",
      height: "50"
    }));
  }
  function renderImageHeader({
    imageIndex: imgIndex
  }) {
    return /*#__PURE__*/React.createElement(View, {
      style: styles.headerContainer
    }, /*#__PURE__*/React.createElement(View, {
      style: styles.flexWidth
    }, /*#__PURE__*/React.createElement(TouchableOpacity, {
      style: styles.closebtnIcon,
      onPress: () => setIsVisibleFullImage(false)
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.closeBtn
    }, "X"))), /*#__PURE__*/React.createElement(View, {
      style: styles.flexWidth
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.header
    }, imgIndex + 1, "/", imagePostsFullSize.length || videoPostsFullSize.length)), /*#__PURE__*/React.createElement(View, {
      style: styles.flexWidth
    }));
  }
  return /*#__PURE__*/React.createElement(Fragment, null, livestreamId.length <= 0 && /*#__PURE__*/React.createElement(Pressable, {
    onPress: onPressPost
  }, textPost && (childrenPosts === null || childrenPosts === void 0 ? void 0 : childrenPosts.length) === 0 && /*#__PURE__*/React.createElement(LinkPreview, {
    text: textPost,
    mentionPositionArr: [...mentionPositionArr]
  }), textPost && (childrenPosts === null || childrenPosts === void 0 ? void 0 : childrenPosts.length) > 0 && /*#__PURE__*/React.createElement(RenderTextWithMention, {
    textPost: textPost,
    mentionPositionArr: [...mentionPositionArr]
  })), pollIds.length > 0 ? /*#__PURE__*/React.createElement(PollContent, {
    post: post,
    pollId: pollIds[0].pollId,
    disabledPoll: disabledPoll,
    showedAllOptions: showedAllOptions
  }) : livestreamId.length > 0 ? /*#__PURE__*/React.createElement(LivestreamContent, {
    post: post,
    onPressPost: onPressPost,
    roomId: livestreamId[0]
  }) : renderMediaPosts(), /*#__PURE__*/React.createElement(ImageView, {
    images: imagePostsFullSize.length > 0 ? imagePostsFullSize : videoPostsFullSize,
    imageIndex: imageIndex,
    visible: visibleFullImage,
    onRequestClose: () => setIsVisibleFullImage(false),
    isVideoButton: videoPosts.length > 0 ? true : false,
    videoPosts: videoPosts,
    HeaderComponent: renderImageHeader
  }));
};
export default /*#__PURE__*/memo(PostContent);
//# sourceMappingURL=index.js.map