import { Alert, View, Pressable, Text, TouchableOpacity, Platform, Modal, useWindowDimensions } from 'react-native';
import { useCallback, useState, useRef, useEffect, memo } from 'react';
import { useCameraDevice, Camera, useCameraFormat, useCameraPermission, useMicrophonePermission } from 'react-native-vision-camera';
import { useStyles } from './styles';
import { SvgXml } from 'react-native-svg';
import { closeIcon, flashOff, flashOn, storyGallery, switchCamera } from '../../../../core/assets/icons/xml';
import { launchImageLibrary } from 'react-native-image-picker';
import * as Progress from 'react-native-progress';
import { msToString } from '../../../../core/utils/time';
import { StoryType } from '../../../enums';
import { useNavigation } from '@react-navigation/native';
import AmityDraftStoryPage from '../Draft';
import { getMediaTypeFromUrl } from '../../../../core/utils/url';
import { SafeAreaView } from 'react-native-safe-area-context';
var ACTIVE_SWITCH = /*#__PURE__*/function (ACTIVE_SWITCH) {
  ACTIVE_SWITCH["camera"] = "camera";
  ACTIVE_SWITCH["video"] = "video";
  return ACTIVE_SWITCH;
}(ACTIVE_SWITCH || {});
const AmityCreateStoryPage = ({
  targetId,
  targetType,
  onCreateStory,
  onDiscardStory
}) => {
  const {
    hasPermission: hasCameraPermission
  } = useCameraPermission();
  const {
    hasPermission: hasMicrophonePermission
  } = useMicrophonePermission();
  const [cameraKey, setCameraKey] = useState(0);
  const {
    width,
    height
  } = useWindowDimensions();
  const isPortrait = width < height;
  const landscapeStyle = !isPortrait && {
    transform: [{
      rotate: '-90deg'
    }],
    height: width - 100,
    alignSelf: 'center'
  };
  const navigation = useNavigation();
  const styles = useStyles();
  const backCamera = useCameraDevice('back');
  const frontCamera = useCameraDevice('front');
  const cameraRef = useRef(null);
  const timerRef = useRef(undefined);
  const [activeSwitch, setActiveSwitch] = useState(ACTIVE_SWITCH.camera);
  const isCamera = activeSwitch === ACTIVE_SWITCH.camera;
  const isVideo = activeSwitch === ACTIVE_SWITCH.video;
  const [flashOnState, setFlashOnState] = useState(false);
  const [activeCamera, setActiveCamera] = useState(backCamera);
  const [isRecording, setIsRecording] = useState(false);
  const [showDraftStory, setShowDraftStory] = useState(false);
  const [mediaTypeData, setMediaTypeData] = useState(null);
  const format = Platform.select({
    ios: useCameraFormat(activeCamera, [{
      photoAspectRatio: 16 / 9
    }, {
      videoAspectRatio: 16 / 9
    }]),
    android: useCameraFormat(activeCamera, [{
      photoAspectRatio: 16 / 9
    }, {
      videoAspectRatio: 16 / 9
    }])
  });
  const activeSwitchColor = {
    backgroundColor: '#ffffff'
  };
  const [totalTime, setTotalTime] = useState(0);
  const [timer, setTimer] = useState('');
  const TIMER_LIMIT = 60000;
  const timerBgColor = (isRecording || totalTime > 0) && {
    backgroundColor: '#FF305A'
  };
  const onStopRecord = useCallback(() => {
    var _cameraRef$current;
    setIsRecording(false);
    clearInterval(timerRef === null || timerRef === void 0 ? void 0 : timerRef.current);
    cameraRef === null || cameraRef === void 0 || (_cameraRef$current = cameraRef.current) === null || _cameraRef$current === void 0 || _cameraRef$current.stopRecording();
  }, []);
  useEffect(() => {
    if (backCamera && !activeCamera) {
      setActiveCamera(backCamera);
    }
  }, [backCamera, activeCamera]);
  useEffect(() => {
    if (hasCameraPermission && hasMicrophonePermission && activeCamera) {
      // Force remount camera component
      setCameraKey(prev => prev + 1);
    }
  }, [hasCameraPermission, hasMicrophonePermission, activeCamera]);
  useEffect(() => {
    if (totalTime === TIMER_LIMIT) return onStopRecord();
    if (!isRecording) return clearInterval(timerRef === null || timerRef === void 0 ? void 0 : timerRef.current);
    timerRef.current = setInterval(() => setTotalTime(prev => prev + 100), 100);
    return () => clearInterval(timerRef === null || timerRef === void 0 ? void 0 : timerRef.current);
  }, [isRecording, onStopRecord, totalTime]);
  useEffect(() => {
    if (totalTime % 1000 === 0) {
      const timerString = msToString(totalTime);
      setTimer(timerString);
    }
  }, [totalTime]);
  const onPressCamera = useCallback(() => {
    setActiveSwitch(ACTIVE_SWITCH.camera);
  }, []);
  const onPressVideo = useCallback(() => {
    setActiveSwitch(ACTIVE_SWITCH.video);
  }, []);
  const onFinishCapture = useCallback(cameraData => {
    setTotalTime(0);
    if (!cameraData) return Alert.alert('Error', 'Error on camera, please try again');
    const name = cameraData.path.split('/').pop();
    const uri = Platform.select({
      ios: cameraData.path,
      android: `file://${cameraData.path}`
    });
    const type = getMediaTypeFromUrl(uri);
    if (!type) {
      Alert.alert('Error', 'Unsupported Media Format');
      return;
    }
    const data = {
      ...cameraData,
      uri: uri,
      name: name
    };
    setMediaTypeData(data);
    setShowDraftStory(true);
  }, []);
  const onPressCameraCapture = useCallback(async () => {
    var _cameraRef$current2;
    const photo = await (cameraRef === null || cameraRef === void 0 || (_cameraRef$current2 = cameraRef.current) === null || _cameraRef$current2 === void 0 ? void 0 : _cameraRef$current2.takePhoto({
      flash: flashOnState ? 'on' : 'off',
      enableShutterSound: false
    }));
    onFinishCapture(photo);
  }, [flashOnState, onFinishCapture]);
  const onStartRecord = useCallback(() => {
    var _cameraRef$current3;
    setIsRecording(true);
    cameraRef === null || cameraRef === void 0 || (_cameraRef$current3 = cameraRef.current) === null || _cameraRef$current3 === void 0 || _cameraRef$current3.startRecording({
      onRecordingFinished: video => onFinishCapture(video),
      onRecordingError: error => {
        if (error.message.includes('no data was received! (null)')) {
          Alert.alert('Video Too Short', 'Please press and hold the button for at least 1 second to record a video.');
        } else Alert.alert('Video Record Error', error.message);
      },
      fileType: 'mp4',
      flash: flashOnState ? 'on' : 'off'
    });
  }, [flashOnState, onFinishCapture]);
  const renderCaptureBtn = useCallback(() => {
    if (isCamera) {
      return /*#__PURE__*/React.createElement(Pressable, {
        style: styles.cameraCaptureBtn,
        onPress: onPressCameraCapture
      }, /*#__PURE__*/React.createElement(View, {
        style: styles.cameraCaptureBtnFill
      }));
    }
    return /*#__PURE__*/React.createElement(Pressable, {
      style: styles.videoCaptureBtn,
      onPressIn: onStartRecord,
      onPressOut: onStopRecord
    }, /*#__PURE__*/React.createElement(View, {
      style: [styles.videoCaptureInnerButton, !isRecording && {
        width: 62,
        height: 62,
        borderRadius: 100
      }]
    }, /*#__PURE__*/React.createElement(Progress.Circle, {
      size: 75,
      progress: totalTime / TIMER_LIMIT,
      borderColor: "transparent",
      color: "red"
    })));
  }, [isCamera, onPressCameraCapture, onStartRecord, onStopRecord, styles, totalTime, isRecording]);
  const onPressBack = useCallback(() => {
    navigation.goBack();
  }, [navigation]);
  const onPressFlash = useCallback(() => {
    setFlashOnState(prev => !prev);
  }, []);
  const onPressSwitch = useCallback(() => {
    setActiveCamera(prev => prev === backCamera ? frontCamera : backCamera);
  }, [backCamera, frontCamera]);
  const onPressGallery = useCallback(async () => {
    const type = isCamera ? 'photo' : StoryType.video;
    const result = await launchImageLibrary({
      mediaType: type,
      quality: 1,
      selectionLimit: 1
    });
    if (!result.didCancel && result.assets && result.assets.length > 0) {
      const data = {
        ...result.assets[0],
        path: result.assets[0].uri
      };
      if (data) {
        onFinishCapture(data);
      } else {
        Alert.alert('Error on media selection');
      }
    }
  }, [isCamera, onFinishCapture]);
  if (!activeCamera) return null;
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    style: styles.wrapper
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.cameraContainer
  }, /*#__PURE__*/React.createElement(Camera, {
    ref: cameraRef,
    key: cameraKey,
    style: [styles.camera, landscapeStyle],
    device: activeCamera,
    isActive: true,
    video: isVideo,
    photo: isCamera,
    audio: true,
    format: format,
    outputOrientation: "device"
  }), renderCaptureBtn(), isVideo && /*#__PURE__*/React.createElement(View, {
    style: [styles.timer, timerBgColor]
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.timerTxt
  }, timer)), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.backBtn,
    onPress: onPressBack
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: closeIcon('#fff'),
    width: 10,
    height: 10
  })), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.flashIcon,
    onPress: onPressFlash
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: flashOnState ? flashOn() : flashOff(),
    width: 24,
    height: 24
  })), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.switchCamera,
    onPress: onPressSwitch
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: switchCamera(),
    width: 32,
    height: 32
  })), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.gallery,
    onPress: onPressGallery
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: storyGallery(),
    width: 32,
    height: 32
  }))), /*#__PURE__*/React.createElement(View, {
    style: styles.switchContainer
  }, /*#__PURE__*/React.createElement(Pressable, {
    style: [styles.switch, isCamera && activeSwitchColor],
    onPress: onPressCamera
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.switchTxt
  }, "Photo")), /*#__PURE__*/React.createElement(Pressable, {
    style: [styles.switch, isVideo && activeSwitchColor],
    onPress: onPressVideo
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.switchTxt
  }, "Video"))), /*#__PURE__*/React.createElement(Modal, {
    visible: showDraftStory,
    animationType: "slide",
    onRequestClose: () => setShowDraftStory(false)
  }, /*#__PURE__*/React.createElement(AmityDraftStoryPage, {
    targetId: targetId,
    targetType: targetType,
    mediaType: mediaTypeData,
    onCreateStory: () => {
      setShowDraftStory(false);
      onCreateStory();
    },
    onDiscardStory: () => {
      setShowDraftStory(false);
      onDiscardStory && onDiscardStory();
    }
  })));
};
export default /*#__PURE__*/memo(AmityCreateStoryPage);
//# sourceMappingURL=Create.js.map