import React, { useCallback, useRef, useState } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import { Camera, useCameraPermission, useCameraDevice, useCameraFormat, PhotoFile, VideoFile } from 'react-native-vision-camera'
import { RecordingButton } from './capture-button'
import { useSharedValue } from 'react-native-reanimated'

export default function CameraScreen(): React.ReactElement {
  const camera = useRef<Camera>(null)
  const { hasPermission, requestPermission } = useCameraPermission()
  const [isCameraInitialized, setIsCameraInitialized] = useState(false)
  const isPressingButton = useSharedValue(false)

  const setIsPressingButton = useCallback(
    (_isPressingButton: boolean) => {
      isPressingButton.value = _isPressingButton
    },
    [isPressingButton],
  )

  const onInitialized = useCallback(() => {
    console.log('Camera initialized!')
    setIsCameraInitialized(true)
  }, [])

  const onMediaCaptured = useCallback(
    (media: PhotoFile | VideoFile) => {
      console.log(`Media captured! ${JSON.stringify(media)}`)
    },
    [],
  )

  if (!hasPermission) {
    requestPermission()
    // Error handling in case they refuse to give permission
    // In the case of our app this might be a requirement
  }

  const device = useCameraDevice('back')
  const format = useCameraFormat(device, [
    { videoResolution: { width: 3048, height: 2160 } },
    { fps: 60 }
  ])

  if (device === null) {
    return <Text>Camera not available. Does user have permissions:  {hasPermission}</Text>
  }

  return (
    hasPermission && (
      <View style={styles.container}>
        <Camera
          ref={camera}
          style={StyleSheet.absoluteFill}
          device={device}
          format={format}
          onInitialized={onInitialized}
          video={true}
          // orientation='portrait' // TODO: figure out what this looks like to the native module
          isActive={true}
        />
        <RecordingButton
          style={styles.captureButton}
          camera={camera}
          onMediaCaptured={onMediaCaptured}
          enabled={isCameraInitialized}
          setIsPressingButton={setIsPressingButton}
        />
      </View>
      
    )
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'black',
  },
  captureButton: {
    position: 'absolute',
    alignSelf: 'center',
    bottom: 20, // should be safe area padding
  },
})