import SwiftUI
import Bedrock

/// Post-crop editor for company logos.
/// Allows resizing the logo within a 3:2 landscape container and selecting a background color.
struct LogoEditorSheet: View {
    @Environment(\.dismiss) private var dismiss
    
    let logoImage: UIImage
    let onComplete: (Data?) -> Void
    
    @State private var zoomScale: CGFloat = 1.0
    @State private var backgroundColor: Color = .white
    @State private var suggestedColors: [Color] = [.white, .black]
    @State private var showingColorPicker = false
    @State private var customColor: Color = .blue
    
    // Zoom range
    private let minZoom: CGFloat = 0.5
    private let maxZoom: CGFloat = 2.0
    
    var body: some View {
        NavigationStack {
            VStack(spacing: Design.Spacing.xLarge) {
                Spacer()
                
                // Logo preview in 3:2 container
                logoPreviewContainer
                
                Spacer()
                
                // Zoom slider
                zoomSliderSection
                
                // Background color picker
                backgroundColorSection
                
                Spacer()
            }
            .padding(.horizontal, Design.Spacing.xLarge)
            .background(Color.AppBackground.secondary)
            .navigationTitle("Edit company logo")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button {
                        onComplete(nil)
                    } label: {
                        Image(systemName: "xmark")
                            .font(.body.bold())
                            .foregroundStyle(Color.Text.primary)
                    }
                }
                
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") {
                        saveAndComplete()
                    }
                    .bold()
                }
            }
        }
        .onAppear {
            extractSuggestedColors()
        }
        .sheet(isPresented: $showingColorPicker) {
            CustomColorPickerSheet(initialColor: customColor) { selectedColor in
                customColor = selectedColor
                backgroundColor = selectedColor
            }
        }
    }
    
    // MARK: - Logo Preview Container
    
    private var logoPreviewContainer: some View {
        GeometryReader { geometry in
            let containerWidth = geometry.size.width
            let containerHeight = containerWidth / Design.CardSize.logoContainerAspectRatio
            
            ZStack {
                // Background color
                Rectangle()
                    .fill(backgroundColor)
                
                // Logo at zoom scale
                Image(uiImage: logoImage)
                    .resizable()
                    .scaledToFit()
                    .scaleEffect(zoomScale)
            }
            .frame(width: containerWidth, height: containerHeight)
            .clipShape(.rect(cornerRadius: Design.CornerRadius.medium))
            .shadow(
                color: Color.Text.secondary.opacity(Design.Opacity.hint),
                radius: Design.Shadow.radiusMedium,
                y: Design.Shadow.offsetSmall
            )
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
        .aspectRatio(Design.CardSize.logoContainerAspectRatio, contentMode: .fit)
    }
    
    // MARK: - Zoom Slider Section
    
    private var zoomSliderSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            Text("Zoom in/out")
                .font(.subheadline)
                .foregroundStyle(Color.Text.secondary)
            
            HStack(spacing: Design.Spacing.medium) {
                Image(systemName: "minus.magnifyingglass")
                    .font(.body)
                    .foregroundStyle(Color.Text.tertiary)
                
                Slider(value: $zoomScale, in: minZoom...maxZoom)
                    .tint(Color.accentColor)
                
                Image(systemName: "plus.magnifyingglass")
                    .font(.body)
                    .foregroundStyle(Color.Text.tertiary)
            }
        }
    }
    
    // MARK: - Background Color Section
    
    private var backgroundColorSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.medium) {
            Text("Change background color")
                .font(.subheadline)
                .foregroundStyle(Color.Text.secondary)
            
            HStack(spacing: Design.Spacing.large) {
                // Suggested label and colors
                Text("Suggested")
                    .font(.subheadline)
                    .foregroundStyle(Color.Text.primary)
                
                HStack(spacing: Design.Spacing.small) {
                    ForEach(suggestedColors.indices, id: \.self) { index in
                        ColorSwatchButton(
                            color: suggestedColors[index],
                            isSelected: backgroundColor == suggestedColors[index]
                        ) {
                            backgroundColor = suggestedColors[index]
                        }
                    }
                }
                
                Spacer()
            }
            
            // Custom color row
            Button {
                showingColorPicker = true
            } label: {
                HStack(spacing: Design.Spacing.small) {
                    Text("Custom color")
                        .font(.subheadline)
                        .foregroundStyle(Color.Text.primary)
                    
                    ColorSwatchButton(
                        color: customColor,
                        isSelected: backgroundColor == customColor
                    ) {
                        backgroundColor = customColor
                    }
                    
                    Spacer()
                    
                    Image(systemName: "chevron.right")
                        .font(.caption)
                        .foregroundStyle(Color.Text.tertiary)
                }
                .contentShape(.rect)
            }
            .buttonStyle(.plain)
        }
    }
    
    // MARK: - Actions
    
    private func extractSuggestedColors() {
        let extracted = logoImage.dominantColors(count: 3)
        if !extracted.isEmpty {
            suggestedColors = extracted
        }
    }
    
    private func saveAndComplete() {
        // Render the final composited image
        guard let finalData = renderFinalLogo() else {
            onComplete(nil)
            return
        }
        onComplete(finalData)
    }
    
    private func renderFinalLogo() -> Data? {
        // Determine canvas size (use a reasonable size for the 3:2 container)
        let canvasWidth: CGFloat = 600
        let canvasHeight = canvasWidth / Design.CardSize.logoContainerAspectRatio
        let canvasSize = CGSize(width: canvasWidth, height: canvasHeight)
        
        // Calculate logo size at current zoom
        let logoAspect = logoImage.size.width / logoImage.size.height
        var logoWidth: CGFloat
        var logoHeight: CGFloat
        
        if logoAspect > Design.CardSize.logoContainerAspectRatio {
            // Logo is wider than container
            logoWidth = canvasWidth * zoomScale
            logoHeight = logoWidth / logoAspect
        } else {
            // Logo is taller than container
            logoHeight = canvasHeight * zoomScale
            logoWidth = logoHeight * logoAspect
        }
        
        let logoRect = CGRect(
            x: (canvasWidth - logoWidth) / 2,
            y: (canvasHeight - logoHeight) / 2,
            width: logoWidth,
            height: logoHeight
        )
        
        // Render using UIGraphicsImageRenderer
        let renderer = UIGraphicsImageRenderer(size: canvasSize)
        let finalImage = renderer.image { context in
            // Fill background
            UIColor(backgroundColor).setFill()
            context.fill(CGRect(origin: .zero, size: canvasSize))
            
            // Draw logo centered
            logoImage.draw(in: logoRect)
        }
        
        return finalImage.pngData()
    }
}

// MARK: - Color Swatch Button

private struct ColorSwatchButton: View {
    let color: Color
    let isSelected: Bool
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            Circle()
                .fill(color)
                .frame(width: Design.CardSize.colorSwatchSize, height: Design.CardSize.colorSwatchSize)
                .overlay(
                    Circle()
                        .stroke(isSelected ? Color.accentColor : Color.Text.tertiary.opacity(Design.Opacity.light), lineWidth: isSelected ? Design.LineWidth.thick : Design.LineWidth.thin)
                )
                .overlay(
                    Circle()
                        .stroke(Color.AppBackground.elevated, lineWidth: Design.LineWidth.medium)
                        .padding(Design.LineWidth.thin)
                        .opacity(isSelected ? 1 : 0)
                )
        }
        .buttonStyle(.plain)
        .accessibilityLabel("Color swatch")
        .accessibilityAddTraits(isSelected ? [.isSelected] : [])
    }
}

// MARK: - Custom Color Picker Sheet

private struct CustomColorPickerSheet: View {
    @Environment(\.dismiss) private var dismiss
    
    let initialColor: Color
    let onSelect: (Color) -> Void
    
    @State private var selectedColor: Color
    
    init(initialColor: Color, onSelect: @escaping (Color) -> Void) {
        self.initialColor = initialColor
        self.onSelect = onSelect
        self._selectedColor = State(initialValue: initialColor)
    }
    
    var body: some View {
        NavigationStack {
            VStack(spacing: Design.Spacing.xLarge) {
                ColorPicker("Select a color", selection: $selectedColor, supportsOpacity: false)
                    .labelsHidden()
                    .scaleEffect(2.0)
                    .frame(height: 100)
                
                // Preview
                RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
                    .fill(selectedColor)
                    .frame(height: 100)
                    .overlay(
                        RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
                            .stroke(Color.Text.tertiary.opacity(Design.Opacity.light), lineWidth: Design.LineWidth.thin)
                    )
                
                Spacer()
            }
            .padding(Design.Spacing.xLarge)
            .navigationTitle("Custom color")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .confirmationAction) {
                    Button("Done") {
                        onSelect(selectedColor)
                        dismiss()
                    }
                    .bold()
                }
            }
        }
        .presentationDetents([.medium])
    }
}

// MARK: - Preview

#Preview {
    LogoEditorSheet(
        logoImage: UIImage(systemName: "building.2.fill")!
    ) { data in
        print(data != nil ? "Saved logo" : "Cancelled")
    }
}
