import { Alert, Image, Text, TouchableOpacity, View } from 'react-native';
import { useCallback, useState, useEffect, memo } from 'react';
import LinearGradient from 'react-native-linear-gradient';
import Video from 'react-native-video';
import { leftLongArrow, rightLongArrow, storyHyperLinkIcon } from '../../../../core/assets/icons/xml';
import { SvgXml } from 'react-native-svg';
import { useStyles } from './styles';
import { CommunityRepository, StoryRepository } from '@amityco/ts-sdk-react-native';
import { ComponentID, ElementID, PageID, StoryType, ImageSizeState } from '../../../enums';
import { useTheme } from 'react-native-paper';
import { useConfigImageUri } from '../../../hooks/useConfigImageUri';
import HyperlinkConfig from './components/HyperLinkConfig';
import { useFile } from '../../../hooks/useFile';
import { getMediaTypeFromUrl } from '../../../../core/utils/url';
import { LoadingOverlay } from '../../../components/legacy/LoadingOverlay';
import mime from 'mime';
import { useToast } from '../../../../core/stores/slices/toastSlice';
import { SafeAreaView } from 'react-native-safe-area-context';
const AmityDraftStoryPage = ({
  targetId,
  targetType,
  mediaType,
  onCreateStory,
  onDiscardStory
}) => {
  var _hyperlink$, _hyperlink$2, _hyperlink$3, _hyperlink$4;
  const type = getMediaTypeFromUrl(mediaType.uri);
  const styles = useStyles();
  const {
    getImage
  } = useFile();
  const [imageDisplayMode, setImageDisplayMode] = useState('fit');
  const [isVisibleModal, setIsVisibleModal] = useState(false);
  const [communityAvatarUrl, setCommunityAvatarUrl] = useState(null);
  const [hyperlink, setHyperlink] = useState(undefined);
  const [loading, setLoading] = useState(false);
  const theme = useTheme();
  const aspectRatioIcon = useConfigImageUri({
    configPath: {
      page: PageID.CreateStoryPage,
      component: ComponentID.WildCardComponent,
      element: ElementID.AspectRatioBtn
    },
    configKey: 'aspect_ratio_icon'
  });
  const hyperLinkIcon = useConfigImageUri({
    configPath: {
      page: PageID.CreateStoryPage,
      component: ComponentID.WildCardComponent,
      element: ElementID.StoryHyperLinkBtn
    },
    configKey: 'hyperlink_button_icon'
  });
  const {
    showToast
  } = useToast();
  useEffect(() => {
    if (!targetId || targetType !== 'community') return setCommunityAvatarUrl(null);
    CommunityRepository.getCommunity(targetId, async ({
      error,
      loading: isLoading,
      data
    }) => {
      if (error) return;
      if (!isLoading) {
        const image = await getImage({
          fileId: data.avatarFileId,
          imageSize: ImageSizeState.small,
          type: 'community'
        });
        setCommunityAvatarUrl(image ?? null);
      }
    })();
  }, [getImage, targetId, targetType]);
  const onPressBack = useCallback(() => {
    Alert.alert('Discard this story?', 'The story will be permanently deleted. It cannot be undone.', [{
      text: 'Cancel',
      style: 'cancel'
    }, {
      text: 'Discard',
      style: 'destructive',
      onPress: () => {
        onDiscardStory();
      }
    }]);
  }, [onDiscardStory]);
  const onPressAspectRatio = useCallback(() => {
    setImageDisplayMode(prev => prev === 'fit' ? 'fill' : 'fit');
  }, []);
  const onPressHyperLink = useCallback(() => {
    setIsVisibleModal(true);
  }, []);
  const onPressShareStory = useCallback(async () => {
    const formData = new FormData();
    const isImage = type === StoryType.image;
    const mimeType = mime.getType(mediaType.uri) ?? (isImage ? 'image/jpeg' : 'video/mp4');
    formData.append('files', {
      uri: mediaType.uri,
      name: mediaType.name,
      type: mimeType
    });
    try {
      setLoading(true);
      if (type === StoryType.image) {
        await StoryRepository.createImageStory('community', targetId, formData, {}, imageDisplayMode, hyperlink);
      } else {
        await StoryRepository.createVideoStory('community', targetId, formData, {}, hyperlink);
      }
      showToast({
        message: 'Successfully shared story.',
        type: 'success'
      });
    } catch (error) {
      showToast({
        message: 'Failed to share story. Please try again.',
        type: 'informative'
      });
    } finally {
      setLoading(false);
      onCreateStory();
    }
  }, [hyperlink, imageDisplayMode, mediaType, onCreateStory, showToast, targetId, type]);
  const onHyperLinkSubmit = useCallback(item => {
    if (!item) {
      setHyperlink(undefined);
      setIsVisibleModal(false);
      return;
    }
    const storyItem = {
      data: item,
      type: 'hyperlink'
    };
    setHyperlink([storyItem]);
    setIsVisibleModal(false);
  }, []);
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.imageContainer
  }, type === StoryType.image ? /*#__PURE__*/React.createElement(React.Fragment, null, imageDisplayMode !== 'fill' && /*#__PURE__*/React.createElement(Image, {
    source: {
      uri: mediaType.uri
    },
    style: styles.blurredBackground,
    resizeMode: "cover",
    blurRadius: 20
  }), /*#__PURE__*/React.createElement(Image, {
    source: {
      uri: mediaType.uri
    },
    style: styles.image,
    resizeMode: imageDisplayMode === 'fill' ? 'cover' : 'contain'
  })) : /*#__PURE__*/React.createElement(Video, {
    paused: loading,
    repeat: true,
    source: {
      uri: mediaType.uri
    },
    style: styles.image,
    resizeMode: imageDisplayMode === 'fill' ? 'cover' : 'contain'
  }), imageDisplayMode === 'fill' && /*#__PURE__*/React.createElement(LinearGradient, {
    colors: ['rgba(0, 0, 0, 0.4)', 'transparent', 'rgba(0, 0, 0, 0.4)'],
    start: {
      x: 0,
      y: 0
    },
    end: {
      x: 0,
      y: 1
    },
    style: styles.storyGradient
  })), (hyperlink === null || hyperlink === void 0 ? void 0 : hyperlink.length) > 0 && /*#__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
  }, (((_hyperlink$ = hyperlink[0]) === null || _hyperlink$ === void 0 || (_hyperlink$ = _hyperlink$.data) === null || _hyperlink$ === void 0 || (_hyperlink$ = _hyperlink$.customText) === null || _hyperlink$ === void 0 ? void 0 : _hyperlink$.length) ?? 0) === 0 ? (_hyperlink$2 = hyperlink[0]) === null || _hyperlink$2 === void 0 || (_hyperlink$2 = _hyperlink$2.data) === null || _hyperlink$2 === void 0 ? void 0 : _hyperlink$2.url : (_hyperlink$3 = hyperlink[0]) === null || _hyperlink$3 === void 0 || (_hyperlink$3 = _hyperlink$3.data) === null || _hyperlink$3 === void 0 ? void 0 : _hyperlink$3.customText)), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.shareStoryBtn,
    onPress: onPressShareStory
  }, /*#__PURE__*/React.createElement(Image, {
    source: communityAvatarUrl ? {
      uri: communityAvatarUrl
    } : require('../../../../core/assets/images/communityAvatar.png'),
    style: styles.avatar
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.shareStoryTxt
  }, "Share story"), /*#__PURE__*/React.createElement(SvgXml, {
    xml: rightLongArrow(theme.colors.baseShade2),
    width: 16,
    height: 16
  })), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.backBtn,
    onPress: onPressBack
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: leftLongArrow('white'),
    width: 32,
    height: 32
  })), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.aspectRatioBtn,
    onPress: onPressAspectRatio
  }, /*#__PURE__*/React.createElement(Image, {
    source: aspectRatioIcon,
    style: styles.aspectRationIcon
  })), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.hyperLinkBtn,
    onPress: onPressHyperLink
  }, /*#__PURE__*/React.createElement(Image, {
    source: hyperLinkIcon,
    style: styles.hyperLinkIcon
  })), /*#__PURE__*/React.createElement(HyperlinkConfig, {
    isVisibleModal: isVisibleModal,
    setIsVisibleModal: setIsVisibleModal,
    onHyperLinkSubmit: onHyperLinkSubmit,
    hyperlinkItem: hyperlink === null || hyperlink === void 0 || (_hyperlink$4 = hyperlink[0]) === null || _hyperlink$4 === void 0 ? void 0 : _hyperlink$4.data
  }), /*#__PURE__*/React.createElement(LoadingOverlay, {
    isLoading: loading
  }));
};
export default /*#__PURE__*/memo(AmityDraftStoryPage);
//# sourceMappingURL=Draft.js.map