"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _reactNative = require("react-native");
var _react = require("react");
var _enums = require("../../../enums");
var _hooks = require("../../../hooks");
var _styles = require("./styles");
var _types = require("../../../types");
var _CloseButtonIconElement = _interopRequireDefault(require("../../../elements/CloseButtonIconElement/CloseButtonIconElement"));
var _native = require("@react-navigation/native");
var _uiSlice = _interopRequireDefault(require("../../../../core/stores/slices/uiSlice"));
var _post = require("../../../../core/utils/post");
var _useAuth = _interopRequireDefault(require("../../../../core/hooks/useAuth"));
var _globalfeedSlice = _interopRequireDefault(require("../../../../core/stores/slices/globalfeedSlice"));
var _feed = require("../../../../core/legacy/feed");
var _TextKeyElement = _interopRequireDefault(require("../../../elements/TextKeyElement/TextKeyElement"));
var _MediaAttachment = _interopRequireDefault(require("../components/MediaAttachment"));
var _DetailedMediaAttachment = _interopRequireDefault(require("../components/DetailedMediaAttachment"));
var _reactNativeImagePicker = require("react-native-image-picker");
var _LoadingImage = _interopRequireDefault(require("../../../components/LoadingImage"));
var _LoadingVideo = _interopRequireDefault(require("../../../components/LoadingVideo"));
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _useMention = _interopRequireDefault(require("../../../hooks/useMention"));
var _errors = require("../../../utils/errors");
var _constants = require("../../../../core/constants");
var _reactNativeControlledMentions = require("react-native-controlled-mentions");
var _store = require("../../../../core/stores/store");
var _BehaviourProvider = require("../../../providers/BehaviourProvider");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const AmityPostComposerPage = ({
  mode,
  targetId,
  targetType,
  community,
  post
}) => {
  var _post$data;
  (0, _hooks.useRequestPermission)({
    onRequestPermissionFailed: () => {
      _reactNative.Linking.openSettings();
    },
    shouldCall: true
  });
  const pageId = _enums.PageID.post_composer_page;
  const {
    AmityPostComposerPageBehavior
  } = (0, _BehaviourProvider.useBehaviour)();
  const {
    isExcluded,
    themeStyles,
    accessibilityId
  } = (0, _hooks.useAmityPage)({
    pageId
  });
  const styles = (0, _styles.useStyles)(themeStyles);
  const {
    getImage
  } = (0, _hooks.useFile)();
  const isEditMode = mode === _types.AmityPostComposerMode.EDIT;
  const navigation = (0, _native.useNavigation)();
  const {
    isKeyboardShowing
  } = (0, _hooks.useKeyboardStatus)();
  const [attachmentBarHeight, setAttachmentBarHeight] = (0, _react.useState)(0);
  const {
    client
  } = (0, _useAuth.default)();
  const dispatch = (0, _store.useUIKitDispatch)();
  const {
    addPostToGlobalFeed,
    updateByPostId
  } = _globalfeedSlice.default.actions;
  const currentUser = (0, _hooks.useUser)((client === null || client === void 0 ? void 0 : client.userId) || '');
  const isCommunityModerator = (0, _hooks.isModerator)(currentUser === null || currentUser === void 0 ? void 0 : currentUser.roles);
  const {
    showToastMessage,
    hideToastMessage
  } = _uiSlice.default.actions;
  const [inputMessage, setInputMessage] = (0, _react.useState)((post === null || post === void 0 || (_post$data = post.data) === null || _post$data === void 0 ? void 0 : _post$data.text) ?? '');
  const [mentionsPosition, setMentionsPosition] = (0, _react.useState)([]);
  const [chosenMediaType, setChosenMediaType] = (0, _react.useState)(null);
  const [displayImages, setDisplayImages] = (0, _react.useState)([]);
  const [displayVideos, setDisplayVideos] = (0, _react.useState)([]);
  const [mentionUsers, setMentionUsers] = (0, _react.useState)([]);
  const [isSwipeup, setIsSwipeup] = (0, _react.useState)(true);
  const [deletedPostIds, setDeletedPostIds] = (0, _react.useState)([]);
  const [isUploading, setIsUploading] = (0, _react.useState)(false);
  const [hasChangedAttachment, setHasChangedAttachment] = (0, _react.useState)(false);
  const [imageErrors, setImageErrors] = (0, _react.useState)(new Set());
  const [videoErrors, setVideoErrors] = (0, _react.useState)(new Set());

  // When community is not provided via props (e.g. PostTypeChoiceModal only
  // dispatches targetId/targetType), fetch it from targetId.
  const [fetchedCommunity, setFetchedCommunity] = (0, _react.useState)(null);
  (0, _react.useEffect)(() => {
    let unsub;
    if (!community && targetType === 'community' && targetId) {
      unsub = _tsSdkReactNative.CommunityRepository.getCommunity(targetId, ({
        data,
        loading,
        error
      }) => {
        if (!loading && !error && data) setFetchedCommunity(data);
      }) ?? undefined;
    }
    return () => {
      var _unsub;
      return (_unsub = unsub) === null || _unsub === void 0 ? void 0 : _unsub();
    };
  }, [community, targetId, targetType]);
  const effectiveCommunity = community ?? fetchedCommunity;
  const privateCommunityId = !(effectiveCommunity !== null && effectiveCommunity !== void 0 && effectiveCommunity.isPublic) && (effectiveCommunity === null || effectiveCommunity === void 0 ? void 0 : effectiveCommunity.communityId);
  const title = isEditMode ? 'Edit Post' : (effectiveCommunity === null || effectiveCommunity === void 0 ? void 0 : effectiveCommunity.displayName) ?? 'My Timeline';
  const isInputValid = !isUploading && imageErrors.size === 0 && videoErrors.size === 0 && inputMessage.trim().length <= _constants.MAXIMUM_POST_CHARACTERS && (inputMessage.trim().length > 0 || displayImages.length > 0 || displayVideos.length > 0) && (displayImages.length <= 10 || displayVideos.length <= 10);
  const {
    renderInput,
    renderSuggestions
  } = (0, _useMention.default)({
    value: inputMessage,
    onChange: setInputMessage,
    communityId: privateCommunityId,
    setMentionUsers: user => {
      setMentionUsers(prev => [...prev, user]);
    },
    setMentionPosition: position => {
      setMentionsPosition(prev => [...prev, position]);
    },
    isMentionLimitReached: mentionUsers.length >= _constants.MAX_MENTION_USERS,
    onMentionLimitReached: () => {
      _reactNative.Alert.alert(_constants.ALERT.MENTION.TOO_MANY.TITLE, _constants.ALERT.MENTION.TOO_MANY.MESSAGE.replace('%s', String(_constants.MAX_MENTION_USERS)), [{
        text: _constants.ALERT.ACTION.OK
      }]);
    }
  });
  const checkIsEditValid = () => {
    var _post$data2;
    return isInputValid && (inputMessage !== (post === null || post === void 0 || (_post$data2 = post.data) === null || _post$data2 === void 0 ? void 0 : _post$data2.text) || hasChangedAttachment);
  };
  const parsePostText = (0, _react.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 getPostInfo = (0, _react.useCallback)(async postArray => {
    try {
      const response = await Promise.all(postArray.map(async id => {
        const {
          data
        } = await (0, _feed.getPostById)(id);
        return data;
      }));
      const images = [];
      const videos = [];
      for (const item of response) {
        if ((item === null || item === void 0 ? void 0 : item.dataType) === 'image') {
          var _item$data;
          const fileId = item === null || item === void 0 || (_item$data = item.data) === null || _item$data === void 0 ? void 0 : _item$data.fileId;
          const url = await getImage({
            fileId: fileId,
            imageSize: _enums.ImageSizeState.full
          });
          images.push({
            url,
            fileId,
            fileName: fileId,
            isUploaded: true,
            postId: item.postId
          });
        } else if ((item === null || item === void 0 ? void 0 : item.dataType) === 'video') {
          var _item$data2, _item$data3, _fileUrls$, _fileUrls$2;
          const fileId = item === null || item === void 0 || (_item$data2 = item.data) === null || _item$data2 === void 0 || (_item$data2 = _item$data2.videoFileId) === null || _item$data2 === void 0 ? void 0 : _item$data2.original;
          const thumbnailFileId = item === null || item === void 0 || (_item$data3 = item.data) === null || _item$data3 === void 0 ? void 0 : _item$data3.thumbnailFileId;
          const fileUrls = await Promise.allSettled([fileId, thumbnailFileId].map(async id => {
            return await getImage({
              fileId: id,
              imageSize: _enums.ImageSizeState.full
            });
          }));
          videos.push({
            //@ts-ignore
            url: (_fileUrls$ = fileUrls[0]) === null || _fileUrls$ === void 0 ? void 0 : _fileUrls$.value,
            fileId: fileId,
            fileName: fileId,
            isUploaded: true,
            //@ts-ignore
            thumbNail: (_fileUrls$2 = fileUrls[1]) === null || _fileUrls$2 === void 0 ? void 0 : _fileUrls$2.value,
            postId: item.postId
          });
        }
      }
      if (images.length > 0) {
        setDisplayImages(images);
      }
      if (videos.length > 0) {
        setDisplayVideos(videos);
      }
    } catch (error) {
      console.log('error: ', error);
    }
  }, [getImage]);
  (0, _react.useEffect)(() => {
    setDeletedPostIds([]);
    return () => setDeletedPostIds([]);
  }, []);
  (0, _react.useEffect)(() => {
    (post === null || post === void 0 ? void 0 : post.children) && getPostInfo(post === null || post === void 0 ? void 0 : post.children);
  }, [getPostInfo, post === null || post === void 0 ? void 0 : post.children]);
  const getMentionPositions = (0, _react.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 = (0, _react.useCallback)(async mentionIds => {
    var _post$data3;
    const {
      data
    } = await _tsSdkReactNative.UserRepository.getUserByIds(mentionIds);
    const users = data.map(user => {
      return {
        ...user,
        name: user.displayName,
        id: user.userId
      };
    });
    setMentionUsers(users);
    const parsedText = parsePostText((post === null || post === void 0 || (_post$data3 = post.data) === null || _post$data3 === void 0 ? void 0 : _post$data3.text) ?? '', users);
    setInputMessage(parsedText);
    return users;
  }, [parsePostText, post === null || post === void 0 ? void 0 : post.data]);
  (0, _react.useEffect)(() => {
    var _post$mentionees;
    if ((post === null || post === void 0 || (_post$mentionees = post.mentionees) === null || _post$mentionees === void 0 ? void 0 : _post$mentionees.length) > 0) {
      var _post$data4, _post$mentionees2, _post$mentionees3;
      const mentionPositions = getMentionPositions((post === null || post === void 0 || (_post$data4 = post.data) === null || _post$data4 === void 0 ? void 0 : _post$data4.text) ?? '', ((_post$mentionees2 = post.mentionees) === null || _post$mentionees2 === void 0 || (_post$mentionees2 = _post$mentionees2[0]) === null || _post$mentionees2 === void 0 ? void 0 : _post$mentionees2.userIds) ?? []);
      getMentionUsers(((_post$mentionees3 = post.mentionees) === null || _post$mentionees3 === void 0 || (_post$mentionees3 = _post$mentionees3[0]) === null || _post$mentionees3 === void 0 ? void 0 : _post$mentionees3.userIds) ?? []);
      setMentionsPosition(mentionPositions);
    } else {
      var _post$data5;
      setInputMessage((post === null || post === void 0 || (_post$data5 = post.data) === null || _post$data5 === void 0 ? void 0 : _post$data5.text) ?? '');
    }
  }, [getMentionPositions, getMentionUsers, post]);
  const onPressClose = (0, _react.useCallback)(() => {
    const routes = navigation.getState().routes;
    if (AmityPostComposerPageBehavior !== null && AmityPostComposerPageBehavior !== void 0 && AmityPostComposerPageBehavior.onPressPost) {
      AmityPostComposerPageBehavior.onPressPost();
    }
    if (routes[routes.length - 2].name === 'PostTargetSelection') {
      navigation.pop(2);
    } else navigation.pop();
  }, [navigation, AmityPostComposerPageBehavior]);
  const onClose = (0, _react.useCallback)(() => {
    _reactNative.Alert.alert('Discard this post', 'The post will be permanently deleted. It cannot be undone', [{
      text: 'Keep Editing',
      style: 'cancel'
    }, {
      text: 'Discard',
      style: 'destructive',
      onPress: () => onPressClose()
    }]);
  }, [onPressClose]);
  const onPressPost = (0, _react.useCallback)(async () => {
    _reactNative.Keyboard.dismiss();
    if (!isInputValid) {
      dispatch(showToastMessage({
        toastMessage: 'Text field cannot be blank !'
      }));
      return;
    }
    dispatch(showToastMessage({
      toastMessage: 'Posting...',
      isLoadingToast: true
    }));
    const mentionedUserIds = (mentionUsers === null || mentionUsers === void 0 ? void 0 : mentionUsers.map(item => item.id)) ?? [];
    const files = chosenMediaType === _enums.mediaAttachment.image ? displayImages : chosenMediaType === _enums.mediaAttachment.video ? displayVideos : [];
    const fileIds = files.map(item => item.fileId);
    const type = (displayImages === null || displayImages === void 0 ? void 0 : displayImages.length) > 0 ? 'image' : (displayVideos === null || displayVideos === void 0 ? void 0 : displayVideos.length) > 0 ? 'video' : 'text';
    try {
      let response;
      if (isEditMode) {
        if ((deletedPostIds === null || deletedPostIds === void 0 ? void 0 : deletedPostIds.length) > 0) {
          await Promise.allSettled(deletedPostIds.map(postId => _tsSdkReactNative.PostRepository.deletePost(postId, false)));
        }
        response = await (0, _feed.editPost)(post.postId, {
          text: (0, _reactNativeControlledMentions.replaceTriggerValues)(inputMessage, ({
            name
          }) => `@${name}`),
          fileIds: fileIds
        }, type, mentionedUserIds.length > 0 ? mentionedUserIds : [], mentionsPosition);
      } else {
        response = await (0, _feed.createPostToFeed)(targetType, targetId, {
          text: (0, _reactNativeControlledMentions.replaceTriggerValues)(inputMessage, ({
            name
          }) => `@${name}`),
          fileIds: fileIds
        }, type, mentionedUserIds.length > 0 ? mentionedUserIds : [], mentionsPosition);
      }
      if (!response) {
        const toastMessage = isEditMode ? 'Failed to edit post' : 'Failed to create post';
        dispatch(showToastMessage({
          toastMessage: toastMessage
        }));
        onPressClose();
        return;
      }
      dispatch(hideToastMessage());
      if (targetType === 'community' && ((effectiveCommunity === null || effectiveCommunity === void 0 ? void 0 : effectiveCommunity.postSetting) === 'ADMIN_REVIEW_POST_REQUIRED' || effectiveCommunity !== null && effectiveCommunity !== void 0 && effectiveCommunity.needApprovalOnPostCreation) && !isCommunityModerator) {
        onPressClose();
        return _reactNative.Alert.alert('Post submitted', 'Your post has been submitted to the pending list. It will be reviewed by community moderator', [{
          text: 'OK'
        }]);
      }
      const formattedPost = await (0, _post.amityPostsFormatter)([response]);
      if (isEditMode) {
        const updatedPost = {
          ...post,
          ...formattedPost[0]
        };
        dispatch(updateByPostId({
          postId: post === null || post === void 0 ? void 0 : post.postId,
          postDetail: {
            ...updatedPost
          }
        }));
      } else {
        dispatch(addPostToGlobalFeed(formattedPost[0]));
      }
      onPressClose();
      return;
    } catch (error) {
      dispatch(hideToastMessage());
      const errorMessage = (0, _errors.getPostErrorMessage)(error, isEditMode);
      dispatch(showToastMessage({
        toastMessage: errorMessage
      }));
    }
  }, [addPostToGlobalFeed, chosenMediaType, effectiveCommunity, deletedPostIds, dispatch, displayImages, displayVideos, hideToastMessage, inputMessage, isEditMode, isInputValid, isCommunityModerator, mentionUsers, mentionsPosition, onPressClose, post, showToastMessage, targetId, targetType, updateByPostId]);
  let tEvents = [];
  const onSwipe = (0, _react.useCallback)(touchEvent => {
    const swipeUp = touchEvent[0] > touchEvent[touchEvent.length - 1];
    const swipeDown = touchEvent[0] < touchEvent[touchEvent.length - 1];
    setIsSwipeup(prev => {
      if (swipeUp && !isKeyboardShowing) return true;
      if (swipeDown) return false;
      return prev;
    });
  }, [isKeyboardShowing]);
  (0, _react.useEffect)(() => {
    isKeyboardShowing && setIsSwipeup(false);
  }, [isKeyboardShowing]);
  const shouldShowDetailAttachment = !isKeyboardShowing && isSwipeup;
  const processMedia = (0, _react.useCallback)(mediaUrls => {
    if (!(mediaUrls !== null && mediaUrls !== void 0 && mediaUrls.length)) return null;
    const mediaObject = mediaUrls.map(url => {
      const fileName = url.substring(url.lastIndexOf('/') + 1);
      return {
        url: url,
        fileName: fileName,
        fileId: '',
        isUploaded: false
      };
    });
    return mediaObject;
  }, []);
  (0, _react.useEffect)(() => {
    if (displayImages !== null && displayImages !== void 0 && displayImages.length) return setChosenMediaType(_enums.mediaAttachment.image);
    if (displayVideos !== null && displayVideos !== void 0 && displayVideos.length) return setChosenMediaType(_enums.mediaAttachment.video);
    return setChosenMediaType(null);
  }, [displayImages === null || displayImages === void 0 ? void 0 : displayImages.length, displayVideos === null || displayVideos === void 0 ? void 0 : displayVideos.length]);
  const pickCamera = (0, _react.useCallback)(async mediaType => {
    if (mediaType === 'photo' && displayImages.length === 10) return _reactNative.Alert.alert('Maximum upload limit reached', "You've reached the upload limit of 10 images. Any additional images will not be saved.");
    if (mediaType === 'video' && displayVideos.length === 10) return _reactNative.Alert.alert('Maximum upload limit reached', "You've reached the upload limit of 10 videos. Any additional videos will not be saved.");
    try {
      const result = await (0, _reactNativeImagePicker.launchCamera)({
        mediaType: mediaType,
        quality: 1,
        presentationStyle: 'fullScreen',
        videoQuality: 'high'
      });
      if (result.assets && result.assets.length > 0 && result.assets[0] !== null && result.assets[0]) {
        var _result$assets$0$type;
        if ((_result$assets$0$type = result.assets[0].type) !== null && _result$assets$0$type !== void 0 && _result$assets$0$type.includes('image')) {
          const imagesArr = [];
          imagesArr.push(result.assets[0].uri);
          const mediaOj = processMedia(imagesArr);
          setDisplayImages(prev => [...prev, ...mediaOj]);
        } else {
          const selectedVideos = result.assets;
          const imageUriArr = selectedVideos.map(item => item.uri);
          const videosArr = [];
          const totalVideos = videosArr.concat(imageUriArr);
          const mediaOj = processMedia(totalVideos);
          setDisplayVideos(prev => [...prev, ...mediaOj]);
        }
      }
    } catch (error) {
      console.log(error);
    }
  }, [displayImages.length, displayVideos.length, processMedia]);
  const onPressCamera = (0, _react.useCallback)(async () => {
    if (displayImages.length > 0) return pickCamera('photo');
    if (displayVideos.length > 0) return pickCamera('video');
    if (_reactNative.Platform.OS === 'ios') return pickCamera('mixed');
    _reactNative.Alert.alert('Open Camera', null, [{
      text: 'Photo',
      onPress: async () => pickCamera('photo')
    }, {
      text: 'Video',
      onPress: async () => pickCamera('video')
    }]);
  }, [displayImages.length, displayVideos.length, pickCamera]);
  const onPressImage = (0, _react.useCallback)(async () => {
    if (displayImages.length === 10) return _reactNative.Alert.alert('Maximum upload limit reached', "You've reached the upload limit of 10 images. Any additional images will not be saved.");
    const result = await (0, _reactNativeImagePicker.launchImageLibrary)({
      mediaType: 'photo',
      quality: 1,
      selectionLimit: 10 - displayImages.length
    });
    if (!result.didCancel && result.assets && result.assets.length > 0) {
      const imageUriArr = result.assets.map(item => item.uri);
      const mediaOj = processMedia(imageUriArr);
      setDisplayImages(prev => {
        const updatedArray = [...prev, ...mediaOj];
        if (updatedArray.length > 10) {
          _reactNative.Alert.alert('Maximum number of images exceeded', 'Maximum number of images that can be uploaded is 10. The rest images will be discarded');
          return updatedArray.slice(0, 10);
        }
        return updatedArray;
      });
    }
  }, [displayImages.length, processMedia]);
  const onPressVideo = (0, _react.useCallback)(async () => {
    if (displayVideos.length === 10) return _reactNative.Alert.alert('Maximum upload limit reached', "You've reached the upload limit of 10 videos. Any additional videos will not be saved.");
    const result = await (0, _reactNativeImagePicker.launchImageLibrary)({
      mediaType: 'video',
      quality: 1,
      selectionLimit: 10 - displayVideos.length
    });
    if (!result.didCancel && result.assets && result.assets.length > 0) {
      const videoUriArr = result.assets.map(item => item.uri);
      const mediaOj = processMedia(videoUriArr);
      setDisplayVideos(prev => {
        const updatedArray = [...prev, ...mediaOj];
        if (updatedArray.length > 10) {
          _reactNative.Alert.alert('Maximum number of videos exceeded', 'Maximum number of videos that can be uploaded is 10. The rest videos will be discarded');
          return updatedArray.slice(0, 10);
        }
        return updatedArray;
      });
    }
  }, [displayVideos.length, processMedia]);
  const handleImageUploadError = (0, _react.useCallback)((hasError, source) => {
    setImageErrors(prev => {
      const newSet = new Set(prev);
      if (hasError) {
        newSet.add(source);
      } else {
        newSet.delete(source);
      }
      return newSet;
    });
  }, []);
  const handleVideoUploadError = (0, _react.useCallback)((hasError, source) => {
    setVideoErrors(prev => {
      const newSet = new Set(prev);
      if (hasError) {
        newSet.add(source);
      } else {
        newSet.delete(source);
      }
      return newSet;
    });
  }, []);
  const handleOnCloseImage = (0, _react.useCallback)((originalPath, _, postId) => {
    setHasChangedAttachment(true);
    setDeletedPostIds(prev => [...prev, postId]);
    setImageErrors(prev => {
      const newSet = new Set(prev);
      newSet.delete(originalPath);
      return newSet;
    });
    setDisplayImages(prevData => {
      const newData = prevData.filter(item => item.url !== originalPath);
      return newData;
    });
  }, []);
  const handleOnCloseVideo = (0, _react.useCallback)((originalPath, _, postId) => {
    setHasChangedAttachment(true);
    setDeletedPostIds(prev => [...prev, postId]);
    setVideoErrors(prev => {
      const newSet = new Set(prev);
      newSet.delete(originalPath);
      return newSet;
    });
    setDisplayVideos(prevData => {
      const newData = prevData.filter(item => item.url !== originalPath);
      return newData;
    });
  }, []);
  const handleOnFinishImage = (0, _react.useCallback)((fileId, fileUrl, fileName, index) => {
    setHasChangedAttachment(true);
    const imageObject = {
      url: fileUrl,
      fileId: fileId,
      fileName: fileName,
      isUploaded: true
    };
    setDisplayImages(prevData => {
      const newData = [...prevData];
      newData[index] = imageObject;
      return newData;
    });
  }, []);
  const handleOnFinishVideo = (0, _react.useCallback)((fileId, fileUrl, fileName, index, _, thumbnail) => {
    setHasChangedAttachment(true);
    const imageObject = {
      url: fileUrl,
      fileId: fileId,
      fileName: fileName,
      isUploaded: true,
      thumbNail: thumbnail
    };
    setDisplayVideos(prevData => {
      const newData = [...prevData];
      newData[index] = imageObject;
      return newData;
    });
  }, []);
  const renderDetailedAttachment = (0, _react.useCallback)(() => {
    if (isEditMode) return null;
    if (shouldShowDetailAttachment) {
      return /*#__PURE__*/React.createElement(_DetailedMediaAttachment.default, {
        onPressCamera: onPressCamera,
        onPressImage: onPressImage,
        onPressVideo: onPressVideo,
        chosenMediaType: chosenMediaType,
        onHeightChange: setAttachmentBarHeight
      });
    }
    return /*#__PURE__*/React.createElement(_MediaAttachment.default, {
      onPressCamera: onPressCamera,
      onPressImage: onPressImage,
      onPressVideo: onPressVideo,
      chosenMediaType: chosenMediaType,
      onHeightChange: setAttachmentBarHeight
    });
  }, [chosenMediaType, isEditMode, onPressCamera, onPressImage, onPressVideo, shouldShowDetailAttachment]);
  if (isExcluded) return null;
  return /*#__PURE__*/React.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    testID: accessibilityId,
    accessibilityLabel: accessibilityId,
    style: styles.container
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.headerContainer
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: onClose,
    hitSlop: 20
  }, /*#__PURE__*/React.createElement(_CloseButtonIconElement.default, {
    pageID: pageId,
    style: styles.closeBtn
  })), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.title
  }, title), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: onPressPost,
    disabled: !isInputValid || !checkIsEditValid()
  }, isEditMode ? /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: [styles.postBtnText, checkIsEditValid() && styles.activePostBtn]
  }, "Save") : /*#__PURE__*/React.createElement(_TextKeyElement.default, {
    pageID: pageId,
    componentID: _enums.ComponentID.WildCardComponent,
    elementID: _enums.ElementID.create_new_post_button,
    style: [styles.postBtnText, isInputValid && styles.activePostBtn]
  }))), /*#__PURE__*/React.createElement(_reactNative.KeyboardAvoidingView, {
    behavior: _reactNative.Platform.OS === 'ios' ? 'padding' : 'height',
    style: styles.inputWrapper
  }, /*#__PURE__*/React.createElement(_reactNative.ScrollView, {
    contentContainerStyle: styles.scrollContainer,
    nestedScrollEnabled: true,
    keyboardShouldPersistTaps: "handled"
  }, renderInput({
    multiline: true,
    placeholder: "What's going on...",
    placeholderTextColor: themeStyles.colors.baseShade3,
    style: styles.input
  }), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.imageContainer
  }, displayImages.length > 0 && /*#__PURE__*/React.createElement(_reactNative.FlatList, {
    nestedScrollEnabled: true,
    scrollEnabled: false,
    data: displayImages,
    renderItem: ({
      item,
      index
    }) => {
      if (!item) return null;
      return /*#__PURE__*/React.createElement(_LoadingImage.default, {
        source: item.url,
        onClose: handleOnCloseImage,
        index: index //TODO: Fix this without index
        ,
        onLoadFinish: handleOnFinishImage,
        onUploadError: handleImageUploadError,
        isUploaded: item.isUploaded,
        fileId: item.fileId,
        fileCount: displayImages.length,
        isEditMode: isEditMode,
        postId: item.postId,
        setIsUploading: setIsUploading
      });
    },
    numColumns: 3
  }), displayVideos.length > 0 && /*#__PURE__*/React.createElement(_reactNative.FlatList, {
    data: displayVideos,
    renderItem: ({
      item,
      index
    }) => {
      if (!item) return null;
      return /*#__PURE__*/React.createElement(_LoadingVideo.default, {
        source: item.url,
        onClose: handleOnCloseVideo,
        index: index //TODO: Fix this without index
        ,
        onLoadFinish: handleOnFinishVideo,
        onUploadError: handleVideoUploadError,
        isUploaded: item.isUploaded,
        fileId: item.fileId,
        thumbNail: item.thumbNail,
        fileCount: displayVideos.length,
        isEditMode: isEditMode,
        postId: item.postId,
        setIsUploading: setIsUploading
      });
    },
    numColumns: 3
  }))), renderSuggestions({
    type: 'post'
  }), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: {
      zIndex: 200,
      minHeight: attachmentBarHeight
    },
    onTouchStart: () => {
      tEvents = [];
    },
    onTouchMove: a => {
      tEvents.push(a.nativeEvent.locationY);
      onSwipe(tEvents);
    }
  }, renderDetailedAttachment())), /*#__PURE__*/React.createElement(_reactNative.StatusBar, {
    backgroundColor: themeStyles.colors.background
  }));
};
var _default = exports.default = /*#__PURE__*/(0, _react.memo)(AmityPostComposerPage);
//# sourceMappingURL=PostComposer.js.map