import SwiftUI
import AVFoundation

/// A camera capture view that takes a photo and returns the image data.
/// Set `shouldDismissOnCapture` to false if you want to handle dismissal yourself (e.g., for overlay cropper).
struct CameraCaptureView: UIViewControllerRepresentable {
    @Environment(\.dismiss) private var dismiss
    
    let shouldDismissOnCapture: Bool
    let onCapture: (Data?) -> Void
    
    init(shouldDismissOnCapture: Bool = true, onCapture: @escaping (Data?) -> Void) {
        self.shouldDismissOnCapture = shouldDismissOnCapture
        self.onCapture = onCapture
    }
    
    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.sourceType = .camera
        picker.delegate = context.coordinator
        picker.allowsEditing = false
        return picker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        let parent: CameraCaptureView
        
        init(_ parent: CameraCaptureView) {
            self.parent = parent
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            if let image = info[.originalImage] as? UIImage {
                let data = image.jpegData(compressionQuality: 0.9)
                parent.onCapture(data)
            } else {
                parent.onCapture(nil)
            }
            if parent.shouldDismissOnCapture {
                parent.dismiss()
            }
        }
        
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            parent.onCapture(nil)
            parent.dismiss()
        }
    }
}

// MARK: - Camera Availability Check

extension CameraCaptureView {
    /// Checks if camera is available on this device
    static var isCameraAvailable: Bool {
        UIImagePickerController.isSourceTypeAvailable(.camera)
    }
}
