import SwiftUI
import PhotosUI
import Bedrock

/// A self-contained image editor flow.
/// Shows source picker first, then presents photo picker or camera as a full-screen cover.
/// The aspect ratio is determined by the imageType.
/// For logos, an additional LogoEditorSheet is shown after cropping.
struct ImageEditorFlow: View {
    @Environment(\.dismiss) private var dismiss
    
    let imageType: CardEditorView.ImageType
    let hasExistingImage: Bool
    let onComplete: (Data?) -> Void  // nil = cancelled/no change, Data = final cropped image
    
    private enum NextAction {
        case library
        case camera
    }
    
    @State private var nextAction: NextAction?
    @State private var showingFullScreenPicker = false
    @State private var showingFullScreenCamera = false
    
    private var aspectRatio: CropAspectRatio {
        imageType.cropAspectRatio
    }
    
    /// Only allow aspect ratio selection for logos
    private var allowAspectRatioSelection: Bool {
        imageType == .logo
    }
    
    /// Whether this is a logo image (needs extra editing step)
    private var isLogoImage: Bool {
        imageType == .logo
    }
    
    var body: some View {
        // Source picker is the base content of this sheet
        sourcePickerView
            .fullScreenCover(isPresented: $showingFullScreenPicker) {
                PhotoPickerFlow(
                    aspectRatio: aspectRatio,
                    allowAspectRatioSelection: allowAspectRatioSelection,
                    isLogoImage: isLogoImage,
                    onComplete: { imageData in
                        showingFullScreenPicker = false
                        if let imageData {
                            onComplete(imageData)
                        }
                        // If nil, we stay on source picker
                    }
                )
            }
            .fullScreenCover(isPresented: $showingFullScreenCamera) {
                CameraFlow(
                    aspectRatio: aspectRatio,
                    allowAspectRatioSelection: allowAspectRatioSelection,
                    isLogoImage: isLogoImage,
                    onComplete: { imageData in
                        showingFullScreenCamera = false
                        if let imageData {
                            onComplete(imageData)
                        }
                        // If nil, we stay on source picker
                    }
                )
            }
    }
    
    // MARK: - Source Picker
    
    private var sourcePickerView: some View {
        NavigationStack {
            VStack(spacing: 0) {
                VStack(spacing: 0) {
                    OptionRow(
                        icon: "photo.on.rectangle",
                        title: String.localized("Select from photo library")
                    ) {
                        showingFullScreenPicker = true
                    }
                    
                    Divider()
                        .padding(.leading, Design.Spacing.xLarge + Design.CardSize.socialIconSize)
                    
                    OptionRow(
                        icon: "camera",
                        title: String.localized("Take photo")
                    ) {
                        showingFullScreenCamera = true
                    }
                    
                    if hasExistingImage {
                        Divider()
                            .padding(.leading, Design.Spacing.xLarge + Design.CardSize.socialIconSize)
                        
                        OptionRow(
                            icon: "trash",
                            title: String.localized("Remove photo"),
                            isDestructive: true
                        ) {
                            onComplete(Data())
                        }
                    }
                }
                .background(Color.AppBackground.card)
                .clipShape(.rect(cornerRadius: Design.CornerRadius.large))
                .padding(.horizontal, Design.Spacing.large)
                .padding(.top, Design.Spacing.medium)
                
                Spacer()
            }
            .background(Color.AppBackground.secondary)
            .navigationTitle(imageType.title)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button {
                        onComplete(nil)
                    } label: {
                        Image(systemName: "xmark")
                            .typography(.bodyEmphasis)
                            .foregroundStyle(Color.Text.primary)
                    }
                }
            }
        }
        .presentationDetents([.height(CGFloat((hasExistingImage ? 3 : 2) * 56 + 100))])
        .presentationDragIndicator(.visible)
    }
}

#Preview {
    Text("Tap to edit")
        .sheet(isPresented: .constant(true)) {
            ImageEditorFlow(
                imageType: .profile,
                hasExistingImage: false
            ) { data in
                Design.debugLog(data != nil ? "Got image" : "Cancelled")
            }
        }
}
