import { memo, useCallback, useEffect, useState } from 'react';
import { TouchableOpacity, View, Text, Modal, FlatList, KeyboardAvoidingView, Platform, ScrollView } from 'react-native';
import { SvgXml } from 'react-native-svg';
import { closeIcon } from '../../../../core/assets/icons/xml';
import { useStyles } from './styles';
import { editPost, getPostById } from '../../../../core/legacy/feed';
import LoadingImage from '../LoadingImage';
import LoadingVideo from '../LoadingVideo';
import useAuth from '../../../../core/hooks/useAuth';
import { useTheme } from 'react-native-paper';
import { PostRepository, UserRepository } from '@amityco/ts-sdk-react-native';
import { amityPostsFormatter } from '../../../../core/utils/post';
import postDetailSlice from '../../../../core/stores/slices/postDetailSlice';
import globalFeedSlice from '../../../../core/stores/slices/globalfeedSlice';
import feedSlice from '../../../../core/stores/slices/feedSlice';
import useMention from '../../../hooks/useMention';
import { replaceTriggerValues } from 'react-native-controlled-mentions';
import { useUIKitDispatch } from '../../../../core/stores/store';
const EditPostModal = ({
  visible,
  onClose,
  postDetail,
  onFinishEdit,
  privateCommunityId
}) => {
  var _postDetail$data;
  const theme = useTheme();
  const styles = useStyles();
  const {
    apiRegion
  } = useAuth();
  const [inputMessage, setInputMessage] = useState((postDetail === null || postDetail === void 0 || (_postDetail$data = postDetail.data) === null || _postDetail$data === void 0 ? void 0 : _postDetail$data.text) ?? '');
  const [displayImages, setDisplayImages] = useState([]);
  const [displayVideos, setDisplayVideos] = useState([]);
  const [mentionPosition, setMentionPosition] = useState([]);
  const [mentionUsers, setMentionUsers] = useState([]);
  const [imagePosts, setImagePosts] = useState([]);
  const [videoPosts, setVideoPosts] = useState([]);
  const [childrenPostArr, setChildrenPostArr] = useState([]);
  const {
    updateByPostId: updateByPostIdGlobalFeed
  } = globalFeedSlice.actions;
  const {
    updatePostDetail
  } = postDetailSlice.actions;
  const {
    updateByPostId
  } = feedSlice.actions;
  const dispatch = useUIKitDispatch();
  const {
    renderInput,
    renderSuggestions
  } = useMention({
    value: inputMessage,
    onChange: setInputMessage,
    communityId: privateCommunityId,
    setMentionUsers: user => {
      setMentionUsers(prev => [...prev, user]);
    },
    setMentionPosition: position => {
      setMentionPosition(prev => [...prev, position]);
    }
  });
  const parsePostText = useCallback((text, mentionUsersArr) => {
    const parsedText = text.replace(/@([\w\s-]+)/g, (_, username) => {
      const mentionee = mentionUsersArr.find(user => user.displayName === username);
      const mentioneeId = mentionee ? mentionee.userId : '';
      return `{@}[${username}](${mentioneeId})`;
    });
    return parsedText;
  }, []);
  const getMentionPositions = useCallback((text, mentioneeIds) => {
    let index = 0;
    let mentions = [];
    let match;
    const mentionRegex = /@([\w-]+)/g;
    while ((match = mentionRegex.exec(text)) !== null) {
      let username = match[1];
      let mentioneeId = mentioneeIds[index++];
      let startIdx = match.index;
      let mention = {
        type: 'user',
        displayName: username,
        index: startIdx,
        length: match[0].length,
        userId: mentioneeId
      };
      mentions.push(mention);
    }
    return mentions;
  }, []);
  const getMentionUsers = useCallback(async mentionIds => {
    var _postDetail$data2;
    const {
      data
    } = await UserRepository.getUserByIds(mentionIds);
    const users = data.map(user => {
      return {
        ...user,
        name: user.displayName,
        id: user.userId
      };
    });
    setMentionUsers(users);
    const parsedText = parsePostText((postDetail === null || postDetail === void 0 || (_postDetail$data2 = postDetail.data) === null || _postDetail$data2 === void 0 ? void 0 : _postDetail$data2.text) ?? '', users);
    setInputMessage(parsedText);
    return users;
  }, []);
  const getPostInfo = useCallback(async postArray => {
    try {
      const response = await Promise.all(postArray.map(async id => {
        const {
          data: post
        } = await getPostById(id);
        return {
          dataType: post.dataType,
          data: post.data
        };
      }));
      response.forEach(item => {
        if ((item === null || item === void 0 ? void 0 : item.dataType) === 'image') {
          setImagePosts(prev => [...prev, `https://api.${apiRegion}.amity.co/api/v3/files/${item === null || item === void 0 ? void 0 : item.data.fileId}/download?size=medium`]);
        } else if ((item === null || item === void 0 ? void 0 : item.dataType) === 'video') {
          setVideoPosts(prev => [...prev, item.data]);
        }
      });
    } catch (error) {
      console.log('error: ', error);
    }
  }, [apiRegion]);
  useEffect(() => {
    if (childrenPostArr.length > 0) {
      getPostInfo(childrenPostArr);
    }
  }, [childrenPostArr, getPostInfo]);
  useEffect(() => {
    getPost(postDetail.postId);
  }, [postDetail.postId, visible]);
  useEffect(() => {
    var _postDetail$mentionee;
    if ((postDetail === null || postDetail === void 0 || (_postDetail$mentionee = postDetail.mentionees) === null || _postDetail$mentionee === void 0 ? void 0 : _postDetail$mentionee.length) > 0) {
      var _postDetail$data3, _postDetail$mentionee2, _postDetail$mentionee3;
      const mentionPositions = getMentionPositions((postDetail === null || postDetail === void 0 || (_postDetail$data3 = postDetail.data) === null || _postDetail$data3 === void 0 ? void 0 : _postDetail$data3.text) ?? '', ((_postDetail$mentionee2 = postDetail.mentionees) === null || _postDetail$mentionee2 === void 0 ? void 0 : _postDetail$mentionee2[0].userIds) ?? []);
      getMentionUsers(((_postDetail$mentionee3 = postDetail.mentionees) === null || _postDetail$mentionee3 === void 0 ? void 0 : _postDetail$mentionee3[0].userIds) ?? []);
      setMentionPosition(mentionPositions);
    } else {
      var _postDetail$data4;
      setInputMessage((postDetail === null || postDetail === void 0 || (_postDetail$data4 = postDetail.data) === null || _postDetail$data4 === void 0 ? void 0 : _postDetail$data4.text) ?? '');
    }
  }, [postDetail]);
  const getPost = postId => {
    const unsubscribePost = PostRepository.getPost(postId, async ({
      data
    }) => {
      setChildrenPostArr(data.children);
    });
    unsubscribePost();
  };
  const handleOnClose = () => {
    onClose && onClose();
  };
  const handleEditPost = async () => {
    const mentionees = mentionUsers.map(user => user.id);
    const files = displayImages.length > 0 ? displayImages : (displayVideos === null || displayVideos === void 0 ? void 0 : displayVideos.length) > 0 ? displayVideos : [];
    const fileIds = files ? files.map(item => item.fileId) : [];
    const type = displayImages.length > 0 ? 'image' : displayVideos.length > 0 ? 'video' : 'text';
    if (type === 'text' && (postDetail === null || postDetail === void 0 ? void 0 : postDetail.children.length) > 0) {
      await Promise.allSettled(postDetail === null || postDetail === void 0 ? void 0 : postDetail.children.map(postId => {
        PostRepository.deletePost(postId, true);
      }));
    }
    const response = await editPost(postDetail.postId, {
      text: replaceTriggerValues(inputMessage, ({
        name
      }) => `@${name}`),
      fileIds: fileIds
    }, type, mentionees, mentionPosition);
    if (response) {
      const formattedPost = await amityPostsFormatter([response]);
      const updatedPost = {
        ...postDetail,
        ...formattedPost[0]
      };
      dispatch(updateByPostId({
        postId: postDetail.postId,
        postDetail: updatedPost
      }));
      dispatch(updateByPostIdGlobalFeed({
        postId: postDetail.postId,
        postDetail: updatedPost
      }));
      dispatch(updatePostDetail(updatedPost));
      onFinishEdit && onFinishEdit({
        text: inputMessage,
        mediaUrls: formattedPost[0].children
      }, type);
      handleOnClose();
    }
  };
  useEffect(() => {
    if (imagePosts.length > 0) {
      const imagesObject = imagePosts.map(url => {
        const parts = url.split('/');
        const fileId = parts[parts.indexOf('files') + 1];
        return {
          url: url,
          fileName: fileId,
          fileId: fileId,
          isUploaded: true
        };
      });
      setDisplayImages(imagesObject);
    }
  }, [imagePosts]);
  const processVideo = useCallback(async () => {
    if (videoPosts.length > 0) {
      const videosObject = await Promise.all(videoPosts.map(async item => {
        return {
          url: `https://api.${apiRegion}.amity.co/api/v3/files/${item.videoFileId.original}/download`,
          fileName: item.videoFileId.original,
          fileId: item.videoFileId.original,
          isUploaded: true,
          thumbNail: `https://api.${apiRegion}.amity.co/api/v3/files/${item.thumbnailFileId}/download`
        };
      }));
      setDisplayVideos(videosObject);
    }
  }, [apiRegion, videoPosts]);
  useEffect(() => {
    processVideo();
  }, [processVideo]);
  const handleOnCloseImage = originalPath => {
    setDisplayImages(prevData => {
      const newData = prevData.filter(item => item.url !== originalPath); // Filter out objects containing the desired value
      return newData; // Remove the element at the specified index
    });
  };
  const handleOnCloseVideo = originalPath => {
    setDisplayVideos(prevData => {
      const newData = prevData.filter(item => item.url !== originalPath); // Filter out objects containing the desired value
      return newData; // Remove the element at the specified index
    });
  };
  return /*#__PURE__*/React.createElement(Modal, {
    visible: visible,
    animationType: "slide"
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.header
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.closeButton,
    onPress: handleOnClose
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: closeIcon(theme.colors.base),
    width: "17",
    height: "17"
  })), /*#__PURE__*/React.createElement(View, {
    style: styles.headerTextContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerText
  }, "Edit Post")), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: handleEditPost,
    style: styles.headerTextContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerText
  }, "Save"))), /*#__PURE__*/React.createElement(KeyboardAvoidingView, {
    behavior: Platform.OS === 'ios' ? 'padding' : 'height',
    keyboardVerticalOffset: Platform.select({
      ios: 100,
      android: 80
    }),
    style: styles.AllInputWrap
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.AllInputWrap
  }, /*#__PURE__*/React.createElement(ScrollView, {
    style: styles.container,
    keyboardShouldPersistTaps: "handled"
  }, renderInput({
    multiline: true,
    style: styles.textInput,
    placeholder: "What's going on...?",
    placeholderTextColor: theme.colors.baseShade3
  }), /*#__PURE__*/React.createElement(View, {
    style: styles.imageContainer
  }, displayImages.length > 0 && /*#__PURE__*/React.createElement(FlatList, {
    data: displayImages,
    renderItem: ({
      item,
      index
    }) => /*#__PURE__*/React.createElement(LoadingImage, {
      source: item.url,
      onClose: handleOnCloseImage,
      index: index,
      isUploaded: item.isUploaded,
      fileId: item.fileId,
      isEditMode: true
    }),
    extraData: displayImages,
    numColumns: 3
  }), displayVideos.length > 0 && /*#__PURE__*/React.createElement(FlatList, {
    data: displayVideos,
    renderItem: ({
      item,
      index
    }) => /*#__PURE__*/React.createElement(LoadingVideo, {
      source: item.url,
      onClose: handleOnCloseVideo,
      index: index,
      isUploaded: item.isUploaded,
      fileId: item.fileId,
      thumbNail: item.thumbNail,
      isEditMode: true
    }),
    numColumns: 3
  }))))), renderSuggestions({
    type: 'post'
  })));
};
export default /*#__PURE__*/memo(EditPostModal);
//# sourceMappingURL=index.js.map