import React, { useCallback, useRef } from 'react';
import {
  Button,
  SafeAreaView,
  ScrollView,
  StatusBar,
  View,
} from 'react-native';
import CameraRoll from '@react-native-community/cameraroll';

import { Camera, useCameraDevices } from 'react-native-vision-camera';

const App = () => {
  const cameraRef = useRef<Camera>(null);

  const devices = useCameraDevices();
  const device = devices.back;

  console.log(JSON.stringify(devices));

  const startRecording = useCallback(() => {
    cameraRef?.current?.startRecording({
      onRecordingFinished: async (video) => {
        console.log(video.path);
        try {
          await CameraRoll.save(video.path);
        } catch (e) {
          console.log(e);
        }
      },
      onRecordingError: (error) => console.error(error),
    });
  }, []);

  const stopRecording = useCallback(async () => {
    await cameraRef?.current?.stopRecording();
  }, []);

  return (
    <SafeAreaView>
      <StatusBar />
      <ScrollView contentInsetAdjustmentBehavior="automatic">
        <View>
          {device !== null && device !== undefined && (
            <Camera
              ref={cameraRef}
              style={{ width: '100%', height: 400 }}
              device={device}
              fps={240}
              isActive={true}
              video
            />
          )}
          <Button title="Start" onPress={startRecording} />
          <Button title="Stop" onPress={stopRecording} />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default App;