import SwiftUI
import Bedrock

struct CameraFlow: View {
    let aspectRatio: CropAspectRatio
    let allowAspectRatioSelection: Bool
    let isLogoImage: Bool
    let onComplete: (Data?) -> Void

    @State private var capturedImageData: Data?
    @State private var showingCropper = false
    @State private var showingLogoEditor = false
    @State private var croppedLogoImage: UIImage?
    @State private var cameraID = UUID()

    var body: some View {
        ZStack {
            if !showingCropper && !showingLogoEditor {
                CameraCaptureView(shouldDismissOnCapture: false) { imageData in
                    if let imageData {
                        capturedImageData = imageData
                        showingCropper = true
                    } else {
                        onComplete(nil)
                    }
                }
                .id(cameraID)
                .ignoresSafeArea()
                .transition(.opacity)
            }

            if showingCropper, let imageData = capturedImageData {
                PhotoCropperSheet(
                    imageData: imageData,
                    aspectRatio: aspectRatio,
                    allowAspectRatioSelection: allowAspectRatioSelection,
                    shouldDismissOnComplete: false
                ) { croppedData in
                    if let croppedData {
                        if isLogoImage, let uiImage = UIImage(data: croppedData) {
                            croppedLogoImage = uiImage
                            showingCropper = false
                            showingLogoEditor = true
                        } else {
                            onComplete(croppedData)
                        }
                    } else {
                        showingCropper = false
                        capturedImageData = nil
                        cameraID = UUID()
                    }
                }
                .transition(.move(edge: .trailing))
            }

            if showingLogoEditor, let logoImage = croppedLogoImage {
                LogoEditorSheet(logoImage: logoImage) { finalData in
                    if let finalData {
                        onComplete(finalData)
                    } else {
                        showingLogoEditor = false
                        croppedLogoImage = nil
                        capturedImageData = nil
                        cameraID = UUID()
                    }
                }
                .transition(.move(edge: .trailing))
            }
        }
        .animation(.easeInOut(duration: Design.Animation.quick), value: showingCropper)
        .animation(.easeInOut(duration: Design.Animation.quick), value: showingLogoEditor)
    }
}
