import { useState, useEffect, useRef, useCallback } from 'react';
import { Animated, Image, Text, TouchableOpacity, Linking, TouchableWithoutFeedback, ActivityIndicator, View, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import Modal from 'react-native-modalbox';
import { usePrevious, isNullOrWhitespace } from './helpers';
import Video from 'react-native-video';
import { SvgXml } from 'react-native-svg';
import { seenIcon, storyCircleCreatePlusIcon, storyCommentIcon, storyHyperLinkIcon, storyLikeIcon, storyLikedIcon, storyThreedotsMenu } from '../../../../core/assets/icons/xml';
import { trash } from '../../../../core/assets/icons';
import { useStyles } from './styles';
import { useTimeDifference } from '../../../../core/hooks/useTimeDifference';
import { useStory } from '../../../hooks/useStory';
import { ElementID, ComponentID, PageID } from '../../../enums/enumUIKitID';
import useConfig from '../../../hooks/useConfig';
import { useNavigation } from '@react-navigation/native';
import BottomSheet from '@devvie/bottom-sheet';
import { StoryRepository } from '@amityco/ts-sdk-react-native';
import CommentList from '../../Social/CommentList/CommentList';
import { useStoryPermission } from '../../../hooks/useStoryPermission';
import { useConfigImageUri } from '../../../hooks/useConfigImageUri';
import { SafeAreaView } from 'react-native-safe-area-context';
export 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 = useStyles();
  const {
    hasStoryPermission
  } = useStoryPermission(userId);
  const {
    getUiKitConfig
  } = useConfig();
  const storyReactionBgColor = ((_getUiKitConfig = getUiKitConfig({
    element: ElementID.StoryRing,
    component: ComponentID.WildCardComponent,
    page: PageID.StoryPage
  })) === null || _getUiKitConfig === void 0 ? void 0 : _getUiKitConfig.background_color) ?? '#2b2b2b';
  const storyCommentBgColor = ((_getUiKitConfig2 = getUiKitConfig({
    page: PageID.StoryPage,
    component: ComponentID.WildCardComponent,
    element: ElementID.StoryCommentBtn
  })) === null || _getUiKitConfig2 === void 0 ? void 0 : _getUiKitConfig2.background_color) ?? '#2b2b2b';
  const storyViewerBgColor = ((_getUiKitConfig3 = getUiKitConfig({
    page: PageID.StoryPage,
    component: ComponentID.WildCardComponent,
    element: ElementID.StoryImpressionBtn
  })) === null || _getUiKitConfig3 === void 0 ? void 0 : _getUiKitConfig3.background_color) ?? '#2b2b2b';
  const storyPlusBgColor = ((_getUiKitConfig4 = getUiKitConfig({
    page: PageID.StoryPage,
    component: ComponentID.WildCardComponent,
    element: ElementID.StoryHyperLinkBtn
  })) === null || _getUiKitConfig4 === void 0 ? void 0 : _getUiKitConfig4.background_color) ?? '#ffffff';
  const [load, setLoad] = useState(true);
  const [pressed, setPressed] = useState(false);
  const [error, setError] = 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 sheetRef = useRef(null);
  const timeDifference = 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 = useNavigation();
  const [totalReaction, setTotalReaction] = useState(reactionCounts);
  const [isLiked, setIsLiked] = useState((myReactions === null || myReactions === void 0 ? void 0 : myReactions.length) > 0);
  const [openCommentSheet, setOpenCommentSheet] = useState(false);
  const {
    handleReaction
  } = useStory();
  const prevCurrentPage = usePrevious(currentPage);
  const [muted, setMuted] = useState(false);
  const hasStoryImpressionPermission = isModerator || content[current].isOwner;
  const muteIcon = useConfigImageUri({
    configPath: {
      page: PageID.StoryPage,
      component: ComponentID.WildCardComponent,
      element: ElementID.SpeakerBtn
    },
    configKey: 'mute_icon'
  });
  const unmuteIcon = useConfigImageUri({
    configPath: {
      page: PageID.StoryPage,
      component: ComponentID.WildCardComponent,
      element: ElementID.SpeakerBtn
    },
    configKey: 'unmute_icon'
  });
  useEffect(() => {
    const mappedStories = stories.map(x => ({
      ...x,
      finish: 0
    }));
    setContent(mappedStories);
  }, [stories]);
  useEffect(() => {
    setIsLiked((myReactions === null || myReactions === void 0 ? void 0 : myReactions.length) > 0);
    setTotalReaction(reactionCounts);
  }, [myReactions, reactionCounts]);
  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 = 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]);
  const start = useCallback(() => {
    setLoad(false);
    startAnimation();
  }, []);
  function startAnimation() {
    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 = useCallback(async () => {
    content[current].markLinkAsClicked();
    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(`Cannot open : ${storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url}`);
    }
  }, [storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url]);
  const onPressAvatar = useCallback(() => {
    if (hasStoryPermission) {
      onClosePress();
      navigation.navigate('CreateStory', {
        targetId: userId,
        targetType: 'community'
      });
    }
  }, [hasStoryPermission]);
  const onPressMenu = useCallback(() => {
    var _sheetRef$current;
    progress.stopAnimation(() => setPressed(true));
    (_sheetRef$current = sheetRef.current) === null || _sheetRef$current === void 0 || _sheetRef$current.open();
  }, []);
  const onPressComment = useCallback(() => {
    progress.stopAnimation(() => setPressed(true));
    setOpenCommentSheet(true);
  }, []);
  const onCloseBottomSheet = useCallback(() => {
    startAnimation();
    setPressed(false);
  }, []);
  const onClosedCommentSheet = useCallback(() => {
    setOpenCommentSheet(false);
    startAnimation();
    setPressed(false);
  }, []);
  const deleteStory = useCallback(async () => {
    try {
      await StoryRepository.softDeleteStory(storyId);
      navigation.goBack();
    } catch (err) {
      Alert.alert('Delete Story Error ', err.message);
    }
  }, []);
  const onPressDelete = useCallback(() => {
    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
    }]);
  }, []);
  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]);
  const onPressProfileName = useCallback(() => {
    onClosePress();
    navigation.navigate('CommunityProfilePage', {
      communityId: userId
    });
  }, [userId, profileName]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(View, {
    style: [styles.container]
  }, /*#__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,
    muted: muted
  }) : /*#__PURE__*/React.createElement(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(View, {
    style: styles.spinnerContainer
  }, /*#__PURE__*/React.createElement(ActivityIndicator, {
    size: "large",
    color: 'white'
  })), error && /*#__PURE__*/React.createElement(View, {
    style: styles.spinnerContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.error
  }, "Story load error")))), /*#__PURE__*/React.createElement(View, {
    style: styles.flexCol
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.animationBarContainer
  }, content.map((_item, barIndex) => {
    return /*#__PURE__*/React.createElement(View, {
      key: barIndex,
      style: [styles.animationBackground]
    }, /*#__PURE__*/React.createElement(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(View, {
    style: styles.userContainer
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.flexRowCenter
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: onPressAvatar,
    hitSlop: 10
  }, /*#__PURE__*/React.createElement(Image, {
    style: styles.avatarImage,
    source: {
      uri: profileImage
    }
  }), hasStoryPermission && /*#__PURE__*/React.createElement(SvgXml, {
    height: 12,
    width: 12,
    style: styles.storyCreateIcon,
    xml: storyCircleCreatePlusIcon(storyPlusBgColor)
  })), /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(Text, {
    onPress: onPressProfileName,
    style: styles.avatarText
  }, profileName), /*#__PURE__*/React.createElement(View, {
    style: styles.flexRowCenter
  }, /*#__PURE__*/React.createElement(Text, {
    style: [styles.avatarSubText,
    // eslint-disable-next-line react-native/no-inline-styles
    {
      marginLeft: 10
    }]
  }, timeDifference, " .", ' '), /*#__PURE__*/React.createElement(Text, {
    style: styles.avatarSubText
  }, "By ", creatorName)))), /*#__PURE__*/React.createElement(View, {
    style: styles.closeIconContainer
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.menuCloseContaier
  }, hasStoryPermission && /*#__PURE__*/React.createElement(TouchableOpacity, {
    hitSlop: 5,
    style: styles.threeDotsMenu,
    onPress: onPressMenu
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: storyThreedotsMenu(),
    width: "25",
    height: "25"
  })), /*#__PURE__*/React.createElement(TouchableOpacity, {
    hitSlop: 5,
    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, {
    style: styles.hyperlinkText
  }, storyHyperLink.customText)), content[current].story_type === 'video' && /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.muteBtn,
    onPress: () => setMuted(prev => !prev)
  }, /*#__PURE__*/React.createElement(Image, {
    source: muted ? muteIcon : unmuteIcon,
    style: styles.muteIcon
  }))), /*#__PURE__*/React.createElement(View, {
    style: styles.footer
  }, hasStoryImpressionPermission ? /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: [styles.seenContainer, {
      backgroundColor: storyViewerBgColor
    }]
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: seenIcon(),
    width: "24",
    height: "24"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.seen
  }, viewer)) : /*#__PURE__*/React.createElement(View, {
    style: styles.seenContainer
  }), /*#__PURE__*/React.createElement(View, {
    style: styles.seenContainer
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: [styles.iconContainer, {
      backgroundColor: storyCommentBgColor
    }],
    onPress: onPressComment
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: storyCommentIcon(),
    width: "24",
    height: "24"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.seen
  }, commentsCounts)), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: [styles.iconContainer, {
      backgroundColor: storyReactionBgColor
    }],
    onPress: onPressReaction
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: isLiked ? storyLikedIcon : storyLikeIcon,
    width: "24",
    height: "24"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.seen
  }, totalReaction))))), openCommentSheet && /*#__PURE__*/React.createElement(Modal, {
    style: styles.bottomSheet,
    isOpen: openCommentSheet,
    onClosed: onClosedCommentSheet,
    position: "bottom",
    swipeToClose: true,
    swipeArea: 250,
    backButtonClose: true,
    coverScreen: true
  }, /*#__PURE__*/React.createElement(KeyboardAvoidingView, {
    behavior: Platform.OS === 'ios' ? 'padding' : 'height',
    style: styles.commentBottomSheet
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.handleBar
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.commentTitle
  }, "Comments"), /*#__PURE__*/React.createElement(View, {
    style: styles.horizontalSperator
  }), /*#__PURE__*/React.createElement(CommentList, {
    postId: storyId,
    postType: "story"
  }))), /*#__PURE__*/React.createElement(BottomSheet, {
    ref: sheetRef,
    onClose: onCloseBottomSheet,
    closeOnDragDown: true,
    height: 120,
    style: styles.deleteBottomSheet
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.deleteBottomSheet
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.deleteBtn,
    onPress: onPressDelete
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: trash(),
    width: 24,
    height: 24
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.deleteStoryTxt
  }, "Delete story")))));
};
export default StoryListItem;
StoryListItem.defaultProps = {
  duration: 10000
};
//# sourceMappingURL=StoryListItem.js.map