import SwiftUI
import Bedrock

/// A combined camera and cropper flow.
/// Shows the camera, and when a photo is taken,
/// immediately overlays the cropper. Both dismiss together when done.
struct CameraWithCropper: View {
    @Environment(\.dismiss) private var dismiss
    
    let aspectRatio: CropAspectRatio
    let onSave: (Data) -> Void
    let onCancel: () -> Void
    
    init(
        aspectRatio: CropAspectRatio = .square,
        onSave: @escaping (Data) -> Void,
        onCancel: @escaping () -> Void
    ) {
        self.aspectRatio = aspectRatio
        self.onSave = onSave
        self.onCancel = onCancel
    }
    
    @State private var capturedImageData: Data?
    @State private var showingCropper = false
    
    var body: some View {
        ZStack {
            // Camera view - don't auto-dismiss so we can show cropper overlay
            CameraCaptureView(shouldDismissOnCapture: false) { imageData in
                if let imageData {
                    capturedImageData = imageData
                    showingCropper = true
                } else {
                    // User cancelled camera
                    onCancel()
                }
            }
            .ignoresSafeArea()
            
            // Cropper overlay
            if showingCropper, let capturedImageData {
                PhotoCropperSheet(
                    imageData: capturedImageData,
                    aspectRatio: aspectRatio,
                    shouldDismissOnComplete: false
                ) { croppedData in
                    if let croppedData {
                        onSave(croppedData)
                    } else {
                        // User cancelled cropper, go back to camera
                        showingCropper = false
                        self.capturedImageData = nil
                    }
                }
                .transition(.move(edge: .trailing))
                .id(aspectRatio.ratio)  // Force recreate cropper when aspect ratio changes
            }
        }
        .animation(.easeInOut(duration: Design.Animation.quick), value: showingCropper)
    }
}

#Preview {
    CameraWithCropper(
        onSave: { _ in print("Saved") },
        onCancel: { print("Cancelled") }
    )
}
