//
//  ToolbarView.swift
//  CheapRetouch
//
//  Tool selection toolbar with contextual inspector panel.
//

import SwiftUI
import UIKit

enum EditTool: String, CaseIterable, Identifiable {
    case person = "Person"
    case object = "Object"
    case brush = "Brush"
    case move = "Move/Zoom"

    var id: String { rawValue }

    var icon: String {
        switch self {
        case .person: return "person.fill"
        case .object: return "circle.dashed"
        case .brush: return "paintbrush.fill"
        case .move: return "arrow.up.and.down.and.arrow.left.and.right"
        }
    }

    var toolDescription: String {
        switch self {
        case .person: return "Tap to remove people"
        case .object: return "Tap to remove objects"
        case .brush: return "Paint to select areas"
        case .move: return "Pinch to zoom, drag to move"
        }
    }
}

struct ToolbarView: View {
    @Bindable var viewModel: EditorViewModel
    @Environment(\.accessibilityReduceMotion) private var reduceMotion
    @ScaledMetric private var toolButtonWidth: CGFloat = 60
    @ScaledMetric private var iconSize: CGFloat = 24

    var body: some View {
        VStack(spacing: 0) {
            Divider()

            // Inspector panel (contextual)
            if viewModel.selectedTool == .brush || viewModel.selectedTool == .person || viewModel.selectedTool == .object {
                inspectorPanel
                    .transition(reduceMotion ? .opacity : .move(edge: .bottom).combined(with: .opacity))
            }

            // Main toolbar
            HStack(spacing: 0) {
                // Tools
                ForEach(EditTool.allCases) { tool in
                    toolButton(for: tool)
                }

                Spacer()

                // Undo/Redo
                Button {
                    Task {
                        await viewModel.undo()
                    }
                } label: {
                    Image(systemName: "arrow.uturn.backward")
                        .font(.title3)
                        .frame(width: 44, height: 44)
                }
                .disabled(!viewModel.canUndo || viewModel.isProcessing)
                .accessibilityLabel("Undo")

                Button {
                    Task {
                        await viewModel.redo()
                    }
                } label: {
                    Image(systemName: "arrow.uturn.forward")
                        .font(.title3)
                        .frame(width: 44, height: 44)
                }
                .disabled(!viewModel.canRedo || viewModel.isProcessing)
                .accessibilityLabel("Redo")
            }
            .padding(.horizontal)
            .padding(.vertical, 8)
            .background(Color(.systemBackground))
        }
        .animation(.easeInOut(duration: 0.2), value: viewModel.selectedTool)
    }

    private func toolButton(for tool: EditTool) -> some View {
        Button {
            viewModel.selectedTool = tool
            // Announce tool selection for VoiceOver
            UIAccessibility.post(notification: .announcement, argument: "\(tool.rawValue) tool selected")
        } label: {
            VStack(spacing: 4) {
                Image(systemName: tool.icon)
                    .font(.system(size: iconSize))
                    .frame(minWidth: 44, minHeight: 32)

                Text(tool.rawValue)
                    .font(.caption2)
            }
            .foregroundStyle(viewModel.selectedTool == tool ? Color.accentColor : Color.secondary)
            .frame(minWidth: toolButtonWidth)
            .frame(minHeight: 44) // Minimum touch target
        }
        .disabled(viewModel.isProcessing)
        .accessibilityLabel("\(tool.rawValue) tool")
        .accessibilityHint(tool.toolDescription)
        .accessibilityAddTraits(viewModel.selectedTool == tool ? .isSelected : [])
    }

    private var inspectorPanel: some View {
        VStack(spacing: 12) {
            Divider()

            if viewModel.selectedTool == .person {
                Text("Tap on a person to select them for removal")
                    .font(.caption)
                    .foregroundStyle(.secondary)
                    .multilineTextAlignment(.center)
                    .accessibilityLabel("Instructions: Tap on a person to select them for removal")
            }

            if viewModel.selectedTool == .object {
                VStack(spacing: 8) {
                    Text("Tap on an object to select it for removal")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                        .multilineTextAlignment(.center)

                    Text("Works best on objects that stand out from background")
                        .font(.caption2)
                        .foregroundStyle(.tertiary)
                        .multilineTextAlignment(.center)
                }
                .accessibilityElement(children: .combine)
                .accessibilityLabel("Tap on an object to select it. Works best on objects that stand out from background. Low-contrast objects may require manual selection with brush.")
            }

            if viewModel.selectedTool == .brush || viewModel.selectedTool == .object {
                HStack {
                    Text("Brush Size")
                        .font(.subheadline)
                    Spacer()
                    Text("\(Int(viewModel.brushSize))px")
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                        .monospacedDigit()
                }

                HStack {
                    Slider(value: $viewModel.brushSize, in: 1...100, step: 1)
                        .accessibilityLabel("Brush size")
                        .accessibilityValue("\(Int(viewModel.brushSize)) pixels")

                    Stepper("", value: $viewModel.brushSize, in: 1...100, step: 1)
                        .labelsHidden()
                        .accessibilityLabel("Brush size stepper")
                        .accessibilityValue("\(Int(viewModel.brushSize)) pixels")
                }

                Toggle(isOn: $viewModel.useEdgeRefinement) {
                    HStack {
                        Image(systemName: "wand.and.rays")
                        Text("Edge Refinement")
                            .font(.subheadline)
                    }
                }
                .toggleStyle(.switch)
                .accessibilityLabel("Edge refinement")
                .accessibilityHint("When enabled, brush strokes snap to nearby edges for cleaner selections")
            }

            // Brush tool action buttons
            if viewModel.selectedTool == .brush {
                HStack(spacing: 12) {
                    // Clear button
                    Button {
                        viewModel.triggerClearBrushStrokes = true
                    } label: {
                        Label("Clear", systemImage: "trash")
                            .font(.subheadline)
                    }
                    .buttonStyle(.bordered)
                    .disabled(viewModel.brushStrokesCount == 0)
                    .accessibilityLabel("Clear all brush strokes")

                    Spacer()

                    // Remove button
                    Button {
                        viewModel.triggerApplyBrushMask = true
                    } label: {
                        Label("Remove", systemImage: "trash")
                            .font(.subheadline)
                    }
                    .buttonStyle(.borderedProminent)
                    .tint(.red)
                    .disabled(viewModel.brushStrokesCount == 0)
                    .accessibilityLabel("Remove selected area")
                }
            }

            HStack {
                Text("Feather")
                    .font(.subheadline)
                Spacer()
                Text("\(Int(viewModel.featherAmount))px")
                    .font(.subheadline)
                    .foregroundStyle(.secondary)
                    .monospacedDigit()
            }

            HStack {
                Slider(value: $viewModel.featherAmount, in: 0...20, step: 1)
                    .accessibilityLabel("Feather amount")
                    .accessibilityValue("\(Int(viewModel.featherAmount)) pixels")

                Stepper("", value: $viewModel.featherAmount, in: 0...20, step: 1)
                    .labelsHidden()
                    .accessibilityLabel("Feather amount stepper")
                    .accessibilityValue("\(Int(viewModel.featherAmount)) pixels")
            }
        }
        .padding(.horizontal)
        .padding(.vertical, 8)
        .background(Color(.secondarySystemBackground))
    }
}

#Preview {
    let viewModel = EditorViewModel()
    return VStack {
        Spacer()
        ToolbarView(viewModel: viewModel)
    }
}
