/**
 * Camera component using react-native-vision-camera (production builds).
 */

import React, { forwardRef, useImperativeHandle, useRef } from "react";
import { StyleSheet } from "react-native";
import { Camera, useCameraDevice } from "react-native-vision-camera";

export interface CameraHandle {
  takePhoto: () => Promise<{ uri: string }>;
}

interface VisionCameraProps {
  flashEnabled?: boolean;
}

export const VisionCamera = forwardRef<CameraHandle, VisionCameraProps>(
  ({ flashEnabled = false }, ref) => {
    const device = useCameraDevice("back");
    const cameraRef = useRef<Camera>(null);

    useImperativeHandle(ref, () => ({
      takePhoto: async () => {
        if (!cameraRef.current) {
          throw new Error("Camera not ready");
        }
        const photo = await cameraRef.current.takePhoto({
          flash: flashEnabled ? "on" : "off",
          enableShutterSound: false,
        });
        return { uri: photo.path };
      },
    }));

    if (!device) {
      return null;
    }

    return (
      <Camera
        ref={cameraRef}
        style={StyleSheet.absoluteFill}
        device={device}
        isActive={true}
        photo={true}
      />
    );
  }
);

VisionCamera.displayName = "VisionCamera";

export { useCameraDevice };
