"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.StoryListItem = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _reactNativeModalbox = _interopRequireDefault(require("react-native-modalbox"));
var _helpers = require("./helpers");
var _reactNativeVideo = _interopRequireDefault(require("react-native-video"));
var _reactNativeSvg = require("react-native-svg");
var _xml = require("../../../../core/assets/icons/xml");
var _icons = require("../../../../core/assets/icons");
var _styles = require("./styles");
var _useTimeDifference = require("../../../../core/hooks/useTimeDifference");
var _useStory = require("../../../hooks/useStory");
var _enumUIKitID = require("../../../enums/enumUIKitID");
var _useConfig = _interopRequireDefault(require("../../../hooks/useConfig"));
var _native = require("@react-navigation/native");
var _bottomSheet = _interopRequireDefault(require("@devvie/bottom-sheet"));
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _CommentList = _interopRequireDefault(require("../../Social/CommentList/CommentList"));
var _useStoryPermission = require("../../../hooks/useStoryPermission");
var _useConfigImageUri = require("../../../hooks/useConfigImageUri");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const StoryListItem = ({
  index,
  key: _key,
  userId,
  profileImage,
  profileName,
  duration,
  onFinish,
  onClosePress,
  stories,
  currentPage,
  onStorySeen,
  isModerator
}) => {
  var _getUiKitConfig, _getUiKitConfig2, _getUiKitConfig3, _getUiKitConfig4, _content$current, _content$current2, _content$current3, _content$current4, _content$current5, _content$current6, _content$current7, _content$current8;
  const styles = (0, _styles.useStyles)();
  const {
    hasStoryPermission
  } = (0, _useStoryPermission.useStoryPermission)(userId);
  const {
    getUiKitConfig
  } = (0, _useConfig.default)();
  const storyReactionBgColor = ((_getUiKitConfig = getUiKitConfig({
    element: _enumUIKitID.ElementID.StoryRing,
    component: _enumUIKitID.ComponentID.WildCardComponent,
    page: _enumUIKitID.PageID.StoryPage
  })) === null || _getUiKitConfig === void 0 ? void 0 : _getUiKitConfig.background_color) ?? '#2b2b2b';
  const storyCommentBgColor = ((_getUiKitConfig2 = getUiKitConfig({
    page: _enumUIKitID.PageID.StoryPage,
    component: _enumUIKitID.ComponentID.WildCardComponent,
    element: _enumUIKitID.ElementID.StoryCommentBtn
  })) === null || _getUiKitConfig2 === void 0 ? void 0 : _getUiKitConfig2.background_color) ?? '#2b2b2b';
  const storyViewerBgColor = ((_getUiKitConfig3 = getUiKitConfig({
    page: _enumUIKitID.PageID.StoryPage,
    component: _enumUIKitID.ComponentID.WildCardComponent,
    element: _enumUIKitID.ElementID.StoryImpressionBtn
  })) === null || _getUiKitConfig3 === void 0 ? void 0 : _getUiKitConfig3.background_color) ?? '#2b2b2b';
  const storyPlusBgColor = ((_getUiKitConfig4 = getUiKitConfig({
    page: _enumUIKitID.PageID.StoryPage,
    component: _enumUIKitID.ComponentID.WildCardComponent,
    element: _enumUIKitID.ElementID.StoryHyperLinkBtn
  })) === null || _getUiKitConfig4 === void 0 ? void 0 : _getUiKitConfig4.background_color) ?? '#ffffff';
  const [load, setLoad] = (0, _react.useState)(true);
  const [pressed, setPressed] = (0, _react.useState)(false);
  const [error, setError] = (0, _react.useState)(false);
  const [content, setContent] = (0, _react.useState)(stories.map(x => ({
    ...x,
    finish: 0
  })));
  const [current, setCurrent] = (0, _react.useState)(0);
  const [storyDuration, setStoryDuration] = (0, _react.useState)(duration);
  const [currentSeek, setCurrentSeek] = (0, _react.useState)(0);
  const progress = (0, _react.useRef)(new _reactNative.Animated.Value(0)).current;
  const sheetRef = (0, _react.useRef)(null);
  const timeDifference = (0, _useTimeDifference.useTimeDifference)((_content$current = content[current]) === null || _content$current === void 0 ? void 0 : _content$current.createdAt, true);
  const storyHyperLink = ((_content$current2 = content[current]) === null || _content$current2 === void 0 || (_content$current2 = _content$current2.items[0]) === null || _content$current2 === void 0 ? void 0 : _content$current2.data) || undefined;
  const creatorName = ((_content$current3 = content[current]) === null || _content$current3 === void 0 ? void 0 : _content$current3.creatorName) ?? '';
  const viewer = ((_content$current4 = content[current]) === null || _content$current4 === void 0 ? void 0 : _content$current4.viewer) ?? 0;
  const storyId = (_content$current5 = content[current]) === null || _content$current5 === void 0 ? void 0 : _content$current5.story_id;
  const reactionCounts = (_content$current6 = content[current]) === null || _content$current6 === void 0 ? void 0 : _content$current6.reactionCounts;
  const commentsCounts = (_content$current7 = content[current]) === null || _content$current7 === void 0 ? void 0 : _content$current7.commentsCounts;
  const myReactions = (_content$current8 = content[current]) === null || _content$current8 === void 0 ? void 0 : _content$current8.myReactions;
  const navigation = (0, _native.useNavigation)();
  const [totalReaction, setTotalReaction] = (0, _react.useState)(reactionCounts);
  const [isLiked, setIsLiked] = (0, _react.useState)((myReactions === null || myReactions === void 0 ? void 0 : myReactions.length) > 0);
  const [openCommentSheet, setOpenCommentSheet] = (0, _react.useState)(false);
  const {
    handleReaction
  } = (0, _useStory.useStory)();
  const prevCurrentPage = (0, _helpers.usePrevious)(currentPage);
  const [muted, setMuted] = (0, _react.useState)(false);
  const hasStoryImpressionPermission = isModerator || content[current].isOwner;
  const muteIcon = (0, _useConfigImageUri.useConfigImageUri)({
    configPath: {
      page: _enumUIKitID.PageID.StoryPage,
      component: _enumUIKitID.ComponentID.WildCardComponent,
      element: _enumUIKitID.ElementID.SpeakerBtn
    },
    configKey: 'mute_icon'
  });
  const unmuteIcon = (0, _useConfigImageUri.useConfigImageUri)({
    configPath: {
      page: _enumUIKitID.PageID.StoryPage,
      component: _enumUIKitID.ComponentID.WildCardComponent,
      element: _enumUIKitID.ElementID.SpeakerBtn
    },
    configKey: 'unmute_icon'
  });
  (0, _react.useEffect)(() => {
    const mappedStories = stories.map(x => ({
      ...x,
      finish: 0
    }));
    setContent(mappedStories);
  }, [stories]);
  (0, _react.useEffect)(() => {
    setIsLiked((myReactions === null || myReactions === void 0 ? void 0 : myReactions.length) > 0);
    setTotalReaction(reactionCounts);
  }, [myReactions, reactionCounts]);
  (0, _react.useEffect)(() => {
    let isPrevious = !!prevCurrentPage && +prevCurrentPage > +currentPage;
    if (isPrevious) {
      setCurrent(content.length - 1);
    } else {
      setCurrent(0);
    }
    let data = [...content];
    data.map((storyItem, storyIndex) => {
      if (isPrevious) {
        storyItem.finish = 1;
        if (storyIndex === content.length - 1) {
          storyItem.finish = 0;
        }
      } else {
        storyItem.finish = 0;
      }
    });
    setContent(data);
    start();
  }, [currentPage]);
  const prevCurrent = (0, _helpers.usePrevious)(current);
  (0, _react.useEffect)(() => {
    if (!(0, _helpers.isNullOrWhitespace)(prevCurrent)) {
      if (prevCurrent) {
        if (+current > +prevCurrent && content[current - 1].story_image === content[current].story_image) {
          start();
        } else if (+current < +prevCurrent && content[current + 1].story_image === content[current].story_image) {
          start();
        }
      }
    }
  }, [current]);
  const start = (0, _react.useCallback)(() => {
    setLoad(false);
    startAnimation();
  }, []);
  function startAnimation() {
    _reactNative.Animated.timing(progress, {
      toValue: 1,
      duration: storyDuration - currentSeek * 1000,
      useNativeDriver: false
    }).start(({
      finished
    }) => {
      if (finished) {
        next();
      }
    });
  }
  function next() {
    setCurrentSeek(0);
    // check if the next content is not empty
    setLoad(true);
    if (current !== content.length - 1) {
      let data = [...content];
      data[current].finish = 1;
      setContent(data);
      setCurrent(current + 1);
      progress.setValue(0);
    } else {
      close('next');
    }
  }
  function previous() {
    setCurrentSeek(0);
    setLoad(true);
    if (current - 1 >= 0) {
      let data = [...content];
      data[current].finish = 0;
      setContent(data);
      setCurrent(current - 1);
      progress.setValue(0);
    } else {
      close('previous');
    }
  }
  function close(state) {
    let data = [...content];
    data.map(x => x.finish = 0);
    setContent(data);
    progress.setValue(0);
    if (currentPage === index) {
      if (onFinish) {
        onFinish(state);
      }
    }
  }
  const onPressHyperLink = (0, _react.useCallback)(async () => {
    content[current].markLinkAsClicked();
    const supported = await _reactNative.Linking.canOpenURL(storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url);
    if (supported) {
      await _reactNative.Linking.openURL(storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url);
    } else {
      _reactNative.Alert.alert(`Cannot open : ${storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url}`);
    }
  }, [storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url]);
  const onPressAvatar = (0, _react.useCallback)(() => {
    if (hasStoryPermission) {
      onClosePress();
      navigation.navigate('CreateStory', {
        targetId: userId,
        targetType: 'community'
      });
    }
  }, [hasStoryPermission]);
  const onPressMenu = (0, _react.useCallback)(() => {
    var _sheetRef$current;
    progress.stopAnimation(() => setPressed(true));
    (_sheetRef$current = sheetRef.current) === null || _sheetRef$current === void 0 || _sheetRef$current.open();
  }, []);
  const onPressComment = (0, _react.useCallback)(() => {
    progress.stopAnimation(() => setPressed(true));
    setOpenCommentSheet(true);
  }, []);
  const onCloseBottomSheet = (0, _react.useCallback)(() => {
    startAnimation();
    setPressed(false);
  }, []);
  const onClosedCommentSheet = (0, _react.useCallback)(() => {
    setOpenCommentSheet(false);
    startAnimation();
    setPressed(false);
  }, []);
  const deleteStory = (0, _react.useCallback)(async () => {
    try {
      await _tsSdkReactNative.StoryRepository.softDeleteStory(storyId);
      navigation.goBack();
    } catch (err) {
      _reactNative.Alert.alert('Delete Story Error ', err.message);
    }
  }, []);
  const onPressDelete = (0, _react.useCallback)(() => {
    _reactNative.Alert.alert('Delete this story?', "This story will be permanently deleted. You'll no longer to see and find this story", [{
      text: 'Cancel',
      onPress: () => {
        var _sheetRef$current2;
        return sheetRef === null || sheetRef === void 0 || (_sheetRef$current2 = sheetRef.current) === null || _sheetRef$current2 === void 0 ? void 0 : _sheetRef$current2.close();
      }
    }, {
      text: 'Delete',
      style: 'destructive',
      onPress: deleteStory
    }]);
  }, []);
  (0, _react.useEffect)(() => {
    if (onStorySeen && currentPage === index) {
      onStorySeen({
        user_id: userId,
        user_image: profileImage,
        user_name: profileName,
        story: content[current]
      });
    }
  }, [currentPage, index, onStorySeen, current]);
  const handleLoadVideo = data => {
    setStoryDuration(data.duration * 1000);
  };
  const onPressReaction = (0, _react.useCallback)(() => {
    handleReaction({
      targetId: storyId,
      reactionName: 'like',
      isLiked
    });
    setTotalReaction(prev => isLiked ? prev - 1 : prev + 1);
    setIsLiked(prev => !prev);
  }, [storyId, isLiked]);
  const onPressProfileName = (0, _react.useCallback)(() => {
    onClosePress();
    navigation.navigate('CommunityProfilePage', {
      communityId: userId
    });
  }, [userId, profileName]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: [styles.container]
  }, /*#__PURE__*/React.createElement(_reactNativeSafeAreaContext.SafeAreaView, null, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.backgroundContainer
  }, content[current].story_type === 'video' ? /*#__PURE__*/React.createElement(_reactNativeVideo.default, {
    onProgress: ({
      currentTime
    }) => setCurrentSeek(currentTime),
    source: {
      uri: content[current].story_video
    },
    style: styles.video,
    resizeMode: "contain",
    controls: false,
    onReadyForDisplay: () => start(),
    paused: content[current].story_page !== currentPage ? true : pressed,
    onLoad: handleLoadVideo,
    muted: muted
  }) : /*#__PURE__*/React.createElement(_reactNative.Image, {
    onError: ({
      nativeEvent: {
        error: err
      }
    }) => err && setError(true),
    onLoadStart: () => setLoad(true),
    onLoadEnd: () => start(),
    source: {
      uri: content[current].story_image
    },
    style: [styles.image],
    resizeMode: "contain"
  }), load && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.spinnerContainer
  }, /*#__PURE__*/React.createElement(_reactNative.ActivityIndicator, {
    size: "large",
    color: 'white'
  })), error && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.spinnerContainer
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.error
  }, "Story load error")))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flexCol
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.animationBarContainer
  }, content.map((_item, barIndex) => {
    return /*#__PURE__*/React.createElement(_reactNative.View, {
      key: barIndex,
      style: [styles.animationBackground]
    }, /*#__PURE__*/React.createElement(_reactNative.Animated.View, {
      style: [
      // eslint-disable-next-line react-native/no-inline-styles
      {
        flex: current === barIndex ? progress : content[barIndex].finish,
        height: 2,
        backgroundColor: 'white'
      }]
    }));
  })), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.userContainer
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flexRowCenter
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: onPressAvatar,
    hitSlop: 10
  }, /*#__PURE__*/React.createElement(_reactNative.Image, {
    style: styles.avatarImage,
    source: {
      uri: profileImage
    }
  }), hasStoryPermission && /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    height: 12,
    width: 12,
    style: styles.storyCreateIcon,
    xml: (0, _xml.storyCircleCreatePlusIcon)(storyPlusBgColor)
  })), /*#__PURE__*/React.createElement(_reactNative.View, null, /*#__PURE__*/React.createElement(_reactNative.Text, {
    onPress: onPressProfileName,
    style: styles.avatarText
  }, profileName), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flexRowCenter
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: [styles.avatarSubText,
    // eslint-disable-next-line react-native/no-inline-styles
    {
      marginLeft: 10
    }]
  }, timeDifference, " .", ' '), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.avatarSubText
  }, "By ", creatorName)))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.closeIconContainer
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.menuCloseContaier
  }, hasStoryPermission && /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    hitSlop: 5,
    style: styles.threeDotsMenu,
    onPress: onPressMenu
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.storyThreedotsMenu)(),
    width: "25",
    height: "25"
  })), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    hitSlop: 5,
    onPress: () => {
      if (onClosePress) {
        onClosePress();
      }
    }
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.whiteText
  }, "X"))))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.pressContainer
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableWithoutFeedback, {
    onPressIn: () => progress.stopAnimation(),
    onLongPress: () => setPressed(true),
    delayLongPress: 300,
    onPressOut: () => {
      setPressed(false);
      startAnimation();
    },
    onPress: () => {
      if (!pressed && !load) {
        previous();
      }
    }
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flex
  })), /*#__PURE__*/React.createElement(_reactNative.TouchableWithoutFeedback, {
    onPressIn: () => progress.stopAnimation(),
    onLongPress: () => setPressed(true),
    delayLongPress: 300,
    onPressOut: () => {
      setPressed(false);
      startAnimation();
    },
    onPress: () => {
      if (!pressed && !load) {
        next();
      }
    }
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flex
  }))), storyHyperLink && /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.hyperlinkContainer,
    onPress: onPressHyperLink
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.storyHyperLinkIcon)('blue'),
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.hyperlinkText
  }, storyHyperLink.customText)), content[current].story_type === 'video' && /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.muteBtn,
    onPress: () => setMuted(prev => !prev)
  }, /*#__PURE__*/React.createElement(_reactNative.Image, {
    source: muted ? muteIcon : unmuteIcon,
    style: styles.muteIcon
  }))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.footer
  }, hasStoryImpressionPermission ? /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: [styles.seenContainer, {
      backgroundColor: storyViewerBgColor
    }]
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.seenIcon)(),
    width: "24",
    height: "24"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.seen
  }, viewer)) : /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.seenContainer
  }), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.seenContainer
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: [styles.iconContainer, {
      backgroundColor: storyCommentBgColor
    }],
    onPress: onPressComment
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.storyCommentIcon)(),
    width: "24",
    height: "24"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.seen
  }, commentsCounts)), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: [styles.iconContainer, {
      backgroundColor: storyReactionBgColor
    }],
    onPress: onPressReaction
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: isLiked ? _xml.storyLikedIcon : _xml.storyLikeIcon,
    width: "24",
    height: "24"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.seen
  }, totalReaction))))), openCommentSheet && /*#__PURE__*/React.createElement(_reactNativeModalbox.default, {
    style: styles.bottomSheet,
    isOpen: openCommentSheet,
    onClosed: onClosedCommentSheet,
    position: "bottom",
    swipeToClose: true,
    swipeArea: 250,
    backButtonClose: true,
    coverScreen: true
  }, /*#__PURE__*/React.createElement(_reactNative.KeyboardAvoidingView, {
    behavior: _reactNative.Platform.OS === 'ios' ? 'padding' : 'height',
    style: styles.commentBottomSheet
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.handleBar
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.commentTitle
  }, "Comments"), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.horizontalSperator
  }), /*#__PURE__*/React.createElement(_CommentList.default, {
    postId: storyId,
    postType: "story"
  }))), /*#__PURE__*/React.createElement(_bottomSheet.default, {
    ref: sheetRef,
    onClose: onCloseBottomSheet,
    closeOnDragDown: true,
    height: 120,
    style: styles.deleteBottomSheet
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.deleteBottomSheet
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.deleteBtn,
    onPress: onPressDelete
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _icons.trash)(),
    width: 24,
    height: 24
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.deleteStoryTxt
  }, "Delete story")))));
};
exports.StoryListItem = StoryListItem;
var _default = exports.default = StoryListItem;
StoryListItem.defaultProps = {
  duration: 10000
};
//# sourceMappingURL=StoryListItem.js.map