import SwiftUI
import PhotosUI
import Bedrock

/// A reusable photo source picker that shows options before accessing the camera roll.
/// Supports: photo library, camera, and remove (if photo exists).
/// Can be extended with additional custom options per use case.
struct PhotoSourcePicker: View {
    @Environment(\.dismiss) private var dismiss
    
    let title: String
    let hasExistingPhoto: Bool
    let additionalOptions: [PhotoSourceOption]
    let onSelectFromLibrary: () -> Void
    let onTakePhoto: () -> Void
    let onRemovePhoto: (() -> Void)?
    let onOptionSelected: ((PhotoSourceOption) -> Void)?
    
    init(
        title: String = "Add photo",
        hasExistingPhoto: Bool = false,
        additionalOptions: [PhotoSourceOption] = [],
        onSelectFromLibrary: @escaping () -> Void,
        onTakePhoto: @escaping () -> Void,
        onRemovePhoto: (() -> Void)? = nil,
        onOptionSelected: ((PhotoSourceOption) -> Void)? = nil
    ) {
        self.title = title
        self.hasExistingPhoto = hasExistingPhoto
        self.additionalOptions = additionalOptions
        self.onSelectFromLibrary = onSelectFromLibrary
        self.onTakePhoto = onTakePhoto
        self.onRemovePhoto = onRemovePhoto
        self.onOptionSelected = onOptionSelected
    }
    
    private var optionCount: Int {
        var count = 2 // Library + Camera
        count += additionalOptions.count
        if hasExistingPhoto { count += 1 } // Remove option
        return count
    }
    
    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // Options list
                VStack(spacing: 0) {
                    // Select from photo library
                    OptionRow(
                        icon: "photo.on.rectangle",
                        title: String.localized("Select from photo library"),
                        action: {
                            onSelectFromLibrary()
                            dismiss()
                        }
                    )
                    
                    Divider()
                        .padding(.leading, Design.Spacing.xLarge + Design.CardSize.socialIconSize)
                    
                    // Take photo
                    OptionRow(
                        icon: "camera",
                        title: String.localized("Take photo"),
                        action: {
                            onTakePhoto()
                            dismiss()
                        }
                    )
                    
                    // Additional custom options
                    ForEach(additionalOptions) { option in
                        Divider()
                            .padding(.leading, Design.Spacing.xLarge + Design.CardSize.socialIconSize)
                        
                        OptionRow(
                            icon: option.icon,
                            title: option.title,
                            action: {
                                onOptionSelected?(option)
                                dismiss()
                            }
                        )
                    }
                    
                    // Remove photo (if exists)
                    if hasExistingPhoto, let onRemovePhoto {
                        Divider()
                            .padding(.leading, Design.Spacing.xLarge + Design.CardSize.socialIconSize)
                        
                        OptionRow(
                            icon: "trash",
                            title: String.localized("Remove photo"),
                            isDestructive: true,
                            action: {
                                onRemovePhoto()
                                dismiss()
                            }
                        )
                    }
                }
                .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(title)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button {
                        dismiss()
                    } label: {
                        Image(systemName: "xmark")
                            .font(.body.bold())
                            .foregroundStyle(Color.Text.primary)
                    }
                }
            }
        }
        .presentationDetents([.height(CGFloat(optionCount * 56 + 100))])
        .presentationDragIndicator(.visible)
    }
}

// MARK: - Option Row

private struct OptionRow: View {
    let icon: String
    let title: String
    var isDestructive: Bool = false
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            HStack(spacing: Design.Spacing.medium) {
                Image(systemName: icon)
                    .font(.body)
                    .foregroundStyle(isDestructive ? Color.red : Color.Text.secondary)
                    .frame(width: Design.CardSize.socialIconSize)
                
                Text(title)
                    .font(.body)
                    .foregroundStyle(isDestructive ? Color.red : Color.Text.primary)
                
                Spacer()
            }
            .padding(.horizontal, Design.Spacing.large)
            .padding(.vertical, Design.Spacing.medium)
            .contentShape(.rect)
        }
        .buttonStyle(.plain)
    }
}

// MARK: - Photo Source Option

/// A custom option that can be added to the photo source picker.
struct PhotoSourceOption: Identifiable {
    let id = UUID()
    let icon: String
    let title: String
    let action: String  // Identifier for handling the action
    
    init(icon: String, title: String, action: String) {
        self.icon = icon
        self.title = title
        self.action = action
    }
}

// MARK: - Common Option Presets

extension PhotoSourceOption {
    /// Option to use a default avatar icon
    static let useIcon = PhotoSourceOption(
        icon: "person.crop.circle",
        title: String.localized("Use icon instead"),
        action: "useIcon"
    )
    
    /// Option to choose from stock photos
    static let stockPhotos = PhotoSourceOption(
        icon: "photo.stack",
        title: String.localized("Choose from stock photos"),
        action: "stockPhotos"
    )
    
    /// Option to import from Files
    static let importFromFiles = PhotoSourceOption(
        icon: "folder",
        title: String.localized("Import from Files"),
        action: "importFromFiles"
    )
}

// MARK: - Preview

#Preview {
    Text("Tap to show picker")
        .sheet(isPresented: .constant(true)) {
            PhotoSourcePicker(
                title: "Add profile picture",
                hasExistingPhoto: true,
                additionalOptions: [],
                onSelectFromLibrary: { print("Library") },
                onTakePhoto: { print("Camera") },
                onRemovePhoto: { print("Remove") }
            )
        }
}
