//
//  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 wire = "Wire"
    case brush = "Brush"

    var id: String { rawValue }

    var icon: String {
        switch self {
        case .person: return "person.fill"
        case .object: return "circle.dashed"
        case .wire: return "line.diagonal"
        case .brush: return "paintbrush.fill"
        }
    }

    var toolDescription: String {
        switch self {
        case .person: return "Tap to remove people"
        case .object: return "Tap to remove objects"
        case .wire: return "Tap to remove wires"
        case .brush: return "Paint to select areas"
        }
    }
}

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 == .wire || 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")
            }

            if viewModel.selectedTool == .wire {
                // Line brush toggle
                HStack {
                    Text("Mode")
                        .font(.subheadline)
                    Spacer()

                    Button {
                        viewModel.toggleLineBrushMode()
                    } label: {
                        HStack(spacing: 4) {
                            Image(systemName: viewModel.isLineBrushMode ? "scribble" : "hand.tap")
                            Text(viewModel.isLineBrushMode ? "Line Brush" : "Tap to Detect")
                                .font(.caption)
                        }
                        .padding(.horizontal, 10)
                        .padding(.vertical, 6)
                        .background(
                            RoundedRectangle(cornerRadius: 8)
                                .fill(viewModel.isLineBrushMode ? Color.accentColor : Color(.tertiarySystemFill))
                        )
                        .foregroundStyle(viewModel.isLineBrushMode ? .white : .primary)
                    }
                    .accessibilityLabel(viewModel.isLineBrushMode ? "Line brush mode active" : "Tap to detect mode active")
                    .accessibilityHint("Double tap to toggle between line brush and tap detection modes")
                }

                if viewModel.isLineBrushMode && !viewModel.lineBrushPath.isEmpty {
                    Button {
                        Task {
                            await viewModel.finishLineBrush()
                        }
                    } label: {
                        Label("Apply Line", systemImage: "checkmark.circle.fill")
                            .font(.subheadline)
                            .frame(maxWidth: .infinity)
                    }
                    .buttonStyle(.borderedProminent)
                    .accessibilityLabel("Apply line brush selection")
                }

                HStack {
                    Text("Line Width")
                        .font(.subheadline)
                    Spacer()
                    Text("\(Int(viewModel.wireWidth))px")
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                        .monospacedDigit()
                }

                HStack {
                    Slider(value: $viewModel.wireWidth, in: 2...20, step: 1)
                        .accessibilityLabel("Wire width")
                        .accessibilityValue("\(Int(viewModel.wireWidth)) pixels")

                    Stepper("", value: $viewModel.wireWidth, in: 2...20, step: 1)
                        .labelsHidden()
                        .accessibilityLabel("Wire width stepper")
                        .accessibilityValue("\(Int(viewModel.wireWidth)) pixels")
                }
            }

            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)
    }
}
