import { useState, useEffect, useRef, useCallback } from 'react';
import { Animated, Image, Text, TouchableOpacity, Linking, TouchableWithoutFeedback, ActivityIndicator, View, SafeAreaView, Alert } from 'react-native';
import GestureRecognizer from 'react-native-swipe-gestures';
import { usePrevious, isNullOrWhitespace } from './helpers';
import Video from 'react-native-video';
import { useFocusEffect } from '@react-navigation/native';
import { SvgXml } from 'react-native-svg';
import { seenIcon, storyCommentIcon, storyHyperLinkIcon, storyLikeIcon, storyLikedIcon } from '../../../../../core/assets/icons/xml';
import { useStyles } from './styles';
import { useTimeDifference } from '../../../../../core/hooks/useTimeDifference';
import { useStory } from '../../../../../core/hooks/useStory';
import { StoryRepository } from '@amityco/ts-sdk-react-native';
export const StoryListItem = ({
  index,
  key,
  userId,
  profileImage,
  profileName,
  duration,
  onFinish,
  onClosePress,
  stories,
  currentPage,
  onStorySeen,
  renderCloseComponent,
  renderSwipeUpComponent,
  renderTextComponent,
  loadedAnimationBarStyle,
  unloadedAnimationBarStyle,
  animationBarContainerStyle,
  storyUserContainerStyle,
  storyImageStyle,
  storyAvatarImageStyle,
  storyContainerStyle
}) => {
  var _content$current;
  const styles = useStyles();
  const [load, setLoad] = useState(true);
  const [pressed, setPressed] = useState(false);
  const [content, setContent] = useState(stories.map(x => ({
    ...x,
    finish: 0
  })));
  const [current, setCurrent] = useState(0);
  const [storyDuration, setStoryDuration] = useState(duration);
  const [currentSeek, setCurrentSeek] = useState(0);
  const progress = useRef(new Animated.Value(0)).current;
  const timeDifference = useTimeDifference(content[current].createdAt, true);
  const storyHyperLink = ((_content$current = content[current]) === null || _content$current === void 0 || (_content$current = _content$current.items[0]) === null || _content$current === void 0 ? void 0 : _content$current.data) || undefined;
  const creatorName = content[current].creatorName ?? '';
  const viewer = content[current].viewer ?? 0;
  const comments = content[current].comments ?? [];
  const storyId = content[current].story_id;
  const [totalReaction, setTotalReaction] = useState(0);
  const [isLiked, setIsLiked] = useState(false);
  const {
    handleReaction
  } = useStory();
  const prevCurrentPage = usePrevious(currentPage);
  useFocusEffect(useCallback(() => {
    const unsubscribe = StoryRepository.getStoryByStoryId(storyId, ({
      error,
      loading,
      data
    }) => {
      if (error) return;
      if (!loading) {
        const myReaction = data.myReactions ?? [];
        setIsLiked(myReaction.length > 0);
        setTotalReaction(data.reactionsCount);
      }
    });
    return () => {
      setPressed(true);
      unsubscribe();
    };
  }, [storyId]));
  useEffect(() => {
    let isPrevious = !!prevCurrentPage && +prevCurrentPage > +currentPage;
    if (isPrevious) {
      setCurrent(content.length - 1);
    } else {
      setCurrent(0);
    }
    let data = [...content];
    data.map((x, i) => {
      if (isPrevious) {
        x.finish = 1;
        if (i === content.length - 1) {
          x.finish = 0;
        }
      } else {
        x.finish = 0;
      }
    });
    setContent(data);
    start();
  }, [currentPage]);
  const prevCurrent = usePrevious(current);
  useEffect(() => {
    if (!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]);
  function start() {
    setLoad(false);
    progress.setValue(0);
    startAnimation();
  }
  function startAnimation() {
    Animated.timing(progress, {
      toValue: 1,
      duration: storyDuration - currentSeek * 1000,
      useNativeDriver: false
    }).start(({
      finished
    }) => {
      if (finished) {
        next();
      }
    });
  }
  function onSwipeUp(_props) {
    if (onClosePress) {
      onClosePress();
    }
    if (content[current].onPress) {
      var _content$current$onPr, _content$current2;
      (_content$current$onPr = (_content$current2 = content[current]).onPress) === null || _content$current$onPr === void 0 || _content$current$onPr.call(_content$current2);
    }
  }
  function onSwipeDown(_props) {
    onClosePress();
  }
  const config = {
    velocityThreshold: 0.3,
    directionalOffsetThreshold: 80
  };
  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 {
      // the next content is empty
      close('next');
    }
  }
  function previous() {
    setCurrentSeek(0);
    // checking if the previous content is not empty
    setLoad(true);
    if (current - 1 >= 0) {
      let data = [...content];
      data[current].finish = 0;
      setContent(data);
      setCurrent(current - 1);
      progress.setValue(0);
    } else {
      // the previous content is empty
      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 = useCallback(async () => {
    const supported = await Linking.canOpenURL(storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url);
    if (supported) {
      await Linking.openURL(storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url);
    } else {
      Alert.alert(`Don't know how to open this URL: ${storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url}`);
    }
  }, [storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url]);
  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 = useCallback(() => {
    handleReaction({
      targetId: storyId,
      reactionName: 'like',
      isLiked
    });
    setTotalReaction(prev => isLiked ? prev - 1 : prev + 1);
    setIsLiked(prev => !prev);
  }, [storyId, isLiked]);
  return /*#__PURE__*/React.createElement(GestureRecognizer, {
    key: key,
    onSwipeUp: onSwipeUp,
    onSwipeDown: onSwipeDown,
    config: config,
    style: [styles.container, storyContainerStyle]
  }, /*#__PURE__*/React.createElement(SafeAreaView, null, /*#__PURE__*/React.createElement(View, {
    style: styles.backgroundContainer
  }, content[current].story_type === 'video' ? /*#__PURE__*/React.createElement(Video, {
    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
  }) : /*#__PURE__*/React.createElement(Image, {
    onLoadEnd: () => start(),
    source: {
      uri: content[current].story_image
    },
    style: [styles.image, storyImageStyle],
    resizeMode: "contain"
  }), load && /*#__PURE__*/React.createElement(View, {
    style: styles.spinnerContainer
  }, /*#__PURE__*/React.createElement(ActivityIndicator, {
    size: "large",
    color: 'white'
  })))), /*#__PURE__*/React.createElement(View, {
    style: styles.flexCol
  }, /*#__PURE__*/React.createElement(View, {
    style: [styles.animationBarContainer, animationBarContainerStyle]
  }, content.map((_index, animKey) => {
    return /*#__PURE__*/React.createElement(View, {
      key: animKey,
      style: [styles.animationBackground, unloadedAnimationBarStyle]
    }, /*#__PURE__*/React.createElement(Animated.View, {
      style: [{
        flex: current === animKey ? progress : content[animKey].finish
      }, styles.animationBar, loadedAnimationBarStyle]
    }));
  })), /*#__PURE__*/React.createElement(View, {
    style: [styles.userContainer, storyUserContainerStyle]
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.flexRowCenter
  }, /*#__PURE__*/React.createElement(Image, {
    style: [styles.avatarImage, storyAvatarImageStyle],
    source: {
      uri: profileImage
    }
  }), typeof renderTextComponent === 'function' ? renderTextComponent({
    item: content[current],
    profileName
  }) : /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Text, {
    style: styles.avatarText
  }, profileName), /*#__PURE__*/React.createElement(View, {
    style: styles.flexRowCenter
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.avatarText
  }, timeDifference), /*#__PURE__*/React.createElement(Text, {
    style: styles.avatarText
  }, "."), /*#__PURE__*/React.createElement(Text, {
    style: styles.avatarText
  }, creatorName)))), /*#__PURE__*/React.createElement(View, {
    style: styles.closeIconContainer
  }, typeof renderCloseComponent === 'function' ? renderCloseComponent({
    onPress: onClosePress,
    item: content[current]
  }) : /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: () => {
      if (onClosePress) {
        onClosePress();
      }
    }
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.whiteText
  }, "X")))), /*#__PURE__*/React.createElement(View, {
    style: styles.pressContainer
  }, /*#__PURE__*/React.createElement(TouchableWithoutFeedback, {
    onPressIn: () => progress.stopAnimation(),
    onLongPress: () => setPressed(true),
    delayLongPress: 300,
    onPressOut: () => {
      setPressed(false);
      startAnimation();
    },
    onPress: () => {
      if (!pressed && !load) {
        previous();
      }
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.flex
  })), /*#__PURE__*/React.createElement(TouchableWithoutFeedback, {
    onPressIn: () => progress.stopAnimation(),
    onLongPress: () => setPressed(true),
    delayLongPress: 300,
    onPressOut: () => {
      setPressed(false);
      startAnimation();
    },
    onPress: () => {
      if (!pressed && !load) {
        next();
      }
    }
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.flex
  })), storyHyperLink && /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.hyperlinkContainer,
    onPress: onPressHyperLink
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: storyHyperLinkIcon('blue'),
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(Text, null, storyHyperLink.customText)))), typeof renderSwipeUpComponent === 'function' ? renderSwipeUpComponent({
    onPress: onSwipeUp,
    item: content[current]
  }) : /*#__PURE__*/React.createElement(View, {
    style: styles.footer
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.seenContainer
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: seenIcon(),
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.seen
  }, viewer)), /*#__PURE__*/React.createElement(View, {
    style: styles.seenContainer
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.iconContainer
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: storyCommentIcon(),
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.seen
  }, comments.length)), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.iconContainer,
    onPress: onPressReaction
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: isLiked ? storyLikedIcon : storyLikeIcon,
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.seen
  }, totalReaction)))));
};
export default StoryListItem;
StoryListItem.defaultProps = {
  duration: 10000
};
//# sourceMappingURL=StoryListItem.js.map