import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Alert,
  Linking,
} from 'react-native';
import React from 'react';
import useCameraApi from '../utils/useCameraAPI.ts';
import {Camera, useCameraDevice} from 'react-native-vision-camera';
import Icon from 'react-native-vector-icons/Entypo.js';
// import {CameraRoll} from '@react-native-camera-roll/camera-roll';

export default function CameraScreen() {
  const {
    requestStoragePermission,
    isPermission,
    requestGPSPermission,
    isGpsPermission,
    sendPhotoFile,
  } = useCameraApi();
  const device = useCameraDevice('back');
  const camera = React.useRef<Camera>(null);

  // const [photoPath, setPhotoPath] = React.useState<string | null>(null);

  React.useEffect(() => {
    // 카메라 및 위치 권한 확인
    const checkPermissions = async () => {
      await requestStoragePermission(permissionGranted => {
        if (!permissionGranted) {
          Alert.alert(
            '카메라 권한이 없습니다.',
            '카메라를 사용하려면 권한을 허용해야 합니다.',
            [{text: '설정으로 이동', onPress: () => Linking.openSettings()}],
          );
          console.log('카메라 권한이 거부되었습니다.');
        }
      });

      await requestGPSPermission(permissionGranted => {
        if (!permissionGranted) {
          Alert.alert(
            '위치 권한이 없습니다.',
            '위치를 사용하려면 권한을 허용해야 합니다.',
            [{text: '설정으로 이동', onPress: () => Linking.openSettings()}],
          );
          console.log('위치 권한이 거부되었습니다.');
        }
      });
    };

    // 디바이스 확인
    if (!device) {
      Alert.alert(
        '카메라 디바이스가 없습니다.',
        '카메라 디바이스를 찾을 수 없습니다.',
      );
    }
    checkPermissions();
  }, [requestStoragePermission, requestGPSPermission, device]);

  // 사진 찍기
  const takePhotoAsync = async () => {
    if (camera.current) {
      try {
        const photo = await camera.current.takePhoto();
        // console.log('Photo:', photo); // photo 확인
        // setPhotoPath(photo.path);
        // await CameraRoll.save(`file://${photo.path}`, {
        //   type: 'photo',
        // });

        // 사진 전송
        await sendPhotoFile(photo.path);
      } catch (error) {
        console.error('Error taking photo:', error);
      }
    }
  };

  const handleTakePhoto = async () => {
    await takePhotoAsync();
  };

  return (
    <View style={{flex: 1}}>
      {isPermission && isGpsPermission ? (
        device ? (
          <>
            <Camera
              style={{flex: 1}}
              device={device}
              isActive={isPermission}
              ref={camera}
              photo={true}
              enableLocation={true}
            />
            {/* 찍은 사진 렌더링 */}
            {/* {photoPath ? (
              <Image source={{uri: `file://${photoPath}`}} style={{flex: 1}} />
            ) : (
              <></>
            )} */}
            <TouchableOpacity
              style={styles.takePicture}
              onPress={handleTakePhoto}>
              <Icon name="circular-graph" size={60} color={'white'} />
            </TouchableOpacity>
          </>
        ) : (
          <Text>디바이스 없다</Text>
        )
      ) : (
        <></>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  takePicture: {
    position: 'absolute',
    bottom: '5%',
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
