import React, { useState, useRef, useEffect } from 'react';
import { View, Text, TouchableOpacity, Image, StyleSheet, PermissionsAndroid, Platform } from 'react-native';
import { Camera, useCameraDevice } from 'react-native-vision-camera';
import { useIsFocused } from '@react-navigation/native';

const CustomCamera = ({ onImageCaptured, onClose }) => {
  const cameraRef = useRef(null);
  const [hasPermission, setHasPermission] = useState(false);
  const [cameraPosition, setCameraPosition] = useState('back');
  const [capturedPhoto, setCapturedPhoto] = useState(null);
  const isFocused = useIsFocused();
  const device = useCameraDevice(cameraPosition);

  useEffect(() => {
    (async () => {
      const status = await Camera.requestCameraPermission();
      console.log(status, "Camera permission status");
      setHasPermission(status === 'granted');
    })();
  }, []);

  const takePhoto = async () => {
    if (cameraRef.current) {
      try {
        const photo = await cameraRef.current.takePhoto({
          flash: 'off',
        });
        const photoUri = Platform.OS === 'android' ? `file://${photo.path}` : photo.path;
        setCapturedPhoto(photoUri);
      } catch (error) {
        console.warn('Error taking photo:', error);
      }
    }
  };

  const flipCamera = () => {
    setCameraPosition(prev => (prev === 'back' ? 'front' : 'back'));
  };

  const confirmPhoto = async () => {
    if (onImageCaptured && capturedPhoto) {
      try {
        const imageInfo = await new Promise((resolve, reject) => {
          Image.getSize(
            capturedPhoto,
            (width, height) => resolve({ width, height }),
            (error) => reject(error)
          );
        });

        const normalizedUri = Platform.OS === 'android' ? capturedPhoto : `file://${capturedPhoto}`;

        onImageCaptured({
          uri: normalizedUri,
          width: imageInfo.width,
          height: imageInfo.height,
          storeData: {},
        });
      } catch (e) {
        console.warn('Failed to get image size:', e);
        onImageCaptured({
          uri: capturedPhoto,
          width: 0,
          height: 0,
          storeData: {},
        });
      }
    }
  };

  const retakePhoto = () => {
    setCapturedPhoto(null);
  };

  if (!device || !hasPermission) {
    return (
      <View style={styles.centered}>
        <Text>Loading Camera...</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {capturedPhoto ? (
        <View style={styles.previewContainer}>
          <Image source={{ uri: capturedPhoto }} style={styles.preview} resizeMode="contain" />
          <View style={styles.buttonRow}>
            <TouchableOpacity onPress={retakePhoto} style={styles.button}>
              <Text>Retake</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={confirmPhoto} style={styles.button}>
              <Text>Use Photo</Text>
            </TouchableOpacity>
          </View>
        </View>
      ) : (
        <>
          {isFocused && !capturedPhoto && (
            <Camera
              style={StyleSheet.absoluteFill}
              device={device}
              isActive={true}
              photo={true}
              ref={cameraRef}
            />
          )}
          <View style={styles.controls}>
            <TouchableOpacity onPress={flipCamera} style={styles.button}>
              <Text>Flip</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={takePhoto} style={styles.captureButton} />
            <TouchableOpacity onPress={onClose} style={styles.button}>
              <Text>Close</Text>
            </TouchableOpacity>
          </View>
        </>
      )}
    </View>
  );
};

export default CustomCamera;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'black',
    height: '100%',
  },
  previewContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    height: '100%',
  },
  preview: {
    width: '100%',
    height: '80%',
  },
  controls: {
    position: 'absolute',
    bottom: 30,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  captureButton: {
    width: 70,
    height: 70,
    borderRadius: 35,
    backgroundColor: 'white',
    borderWidth: 5,
    borderColor: 'gray',
  },
  button: {
    backgroundColor: 'white',
    padding: 10,
    borderRadius: 8,
  },
  buttonRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 20,
    width: '100%',
  },
  centered: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
