import SwiftUI
import AppKit

struct ContentView: View {
    @StateObject private var appState = AppState.shared
    @StateObject private var modelManager = ModelManager.shared
    @State private var shouldCapitalize = false // Default to OFF
    @State private var copyOnStop = true
    @AppStorage("hasCompletedOnboarding") private var hasCompletedOnboarding = false
    @State private var showOnboarding = false
    @State private var showDictationKeyTip = false
    
    private var recognizer: ParakeetSpeechRecognizer {
        appState.recognizer
    }
    
    var body: some View {
        VStack(spacing: 20) {
            // Status indicator
            HStack {
                if modelManager.modelState == .downloading {
                    ProgressView()
                        .scaleEffect(0.8)
                        .padding(.trailing, 4)
                    Text("Downloading model...")
                        .font(.headline)
                        .foregroundColor(.blue)
                } else {
                Circle()
                    .fill(recognizer.isRecording ? Color.red : Color.gray)
                    .frame(width: 12, height: 12)
                
                Text(recognizer.isRecording ? "Recording..." : "Ready")
                    .font(.headline)
                    .foregroundColor(.secondary)
                }
            }
            
            // Main transcript area
            ScrollViewReader { proxy in
            ScrollView {
                    VStack(alignment: .leading, spacing: 0) {
                        if recognizer.transcript.isEmpty {
                            Text("Press the dictation key to start dictation")
                                .font(.system(size: 16))
                                .foregroundColor(.secondary)
                                .frame(maxWidth: .infinity, alignment: .leading)
                                .padding()
                                .id("placeholder")
                        } else {
                            Text(recognizer.transcript)
                    .font(.system(size: 16))
                                .foregroundColor(.primary)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding()
                    .textSelection(.enabled)
                                .id("transcript")
                        }
                    }
            }
            .frame(width: 500, height: 300)
            .background(Color(nsColor: .textBackgroundColor))
            .cornerRadius(8)
                .onChange(of: recognizer.transcript) { _, newValue in
                    if !newValue.isEmpty {
                        withAnimation {
                            proxy.scrollTo("transcript", anchor: .bottom)
                        }
                    }
                }
            }
            
            // Controls
            VStack(spacing: 12) {
                HStack(spacing: 16) {
                    Button(action: {
                        showDictationKeyTip = true
                    }) {
                        HStack {
                            if modelManager.modelState == .downloading {
                                ProgressView()
                                    .scaleEffect(0.7)
                                Text("Preparing...")
                                    .font(.headline)
                            } else {
                                Image(systemName: "mic")
                                .font(.title2)
                                Text(recognizer.isRecording ? "Stop (dictation key)" : "Record (dictation key)")
                                .font(.headline)
                            }
                        }
                        .frame(width: 140)
                    }
                    .buttonStyle(.borderedProminent)
                    .tint(recognizer.isRecording ? .red : .blue)
                    .keyboardShortcut("r", modifiers: .command)
                    .disabled(modelManager.modelState == .downloading)
                    
                    Button(action: {
                        recognizer.clearTranscript()
                    }) {
                        HStack {
                            Image(systemName: "trash")
                            Text("Clear")
                        }
                        .frame(width: 140)
                    }
                    .disabled(recognizer.transcript.isEmpty)
                    
                    Button(action: {
                        NSPasteboard.general.clearContents()
                        NSPasteboard.general.setString(recognizer.transcript, forType: .string)
                    }) {
                        HStack {
                            Image(systemName: "doc.on.clipboard")
                            Text("Copy")
                        }
                        .frame(width: 140)
                    }
                    .disabled(recognizer.transcript.isEmpty)
                    .keyboardShortcut("c", modifiers: [.command, .shift])
                }
                
                Divider()
                
                // Settings toggles
                VStack(spacing: 8) {
                    Toggle("Capitalize", isOn: $shouldCapitalize)
                        .toggleStyle(.switch)
                    
                    Toggle("Auto-copy on stop", isOn: $copyOnStop)
                        .toggleStyle(.switch)
                    
                    Toggle("Restore clipboard after paste", isOn: Binding(
                        get: { appState.restoreClipboard },
                        set: { _ in appState.toggleClipboardRestore() }
                    ))
                    .toggleStyle(.switch)
                    .help("When OFF, transcription stays in clipboard")
                }
                .font(.subheadline)
            }
            
            // Error display
            if let error = recognizer.errorMessage {
                Text(error)
                    .font(.caption)
                    .foregroundColor(.red)
                    .padding(.horizontal)
            }

            Text("Use the dictation key (microphone icon) to start or stop recording.")
                .font(.footnote)
                .foregroundColor(.secondary)
        }
        .padding(20)
        .frame(minWidth: 540, minHeight: 500)
        .onAppear {
            showOnboarding = !hasCompletedOnboarding
        }
        .sheet(isPresented: $showOnboarding) {
            OnboardingView(showOnboarding: $showOnboarding, hasCompletedOnboarding: $hasCompletedOnboarding)
        }
        .alert("Use the dictation key", isPresented: $showDictationKeyTip) {
            Button("OK", role: .cancel) { }
        } message: {
            Text("Press the dictation key with the microphone icon to start or stop recording.")
        }
    }
}

struct OnboardingStep: Identifiable {
    let id = UUID()
    let title: String
    let description: String
    let systemImage: String
    let settingsURL: String?
}

struct OnboardingView: View {
    @Binding var showOnboarding: Bool
    @Binding var hasCompletedOnboarding: Bool
    @State private var currentStep = 0

    private let steps: [OnboardingStep] = [
        OnboardingStep(
            title: "Allow Accessibility",
            description: "Enable accessibility access so lowercase can paste text for you.",
            systemImage: "figure.wave.circle.fill",
            settingsURL: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
        ),
        OnboardingStep(
            title: "Allow Input Monitoring",
            description: "Grant input monitoring so dictation key presses can be detected.",
            systemImage: "keyboard",
            settingsURL: "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent"
        ),
        OnboardingStep(
            title: "Allow Microphone",
            description: "Let lowercase capture your speech for transcription.",
            systemImage: "mic.fill",
            settingsURL: "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"
        ),
        OnboardingStep(
            title: "Select Your Model",
            description: "Pick a speech model in Settings. The download begins the first time you record.",
            systemImage: "slider.horizontal.3",
            settingsURL: nil
        )
    ]

    var body: some View {
        VStack(spacing: 20) {
            TabView(selection: $currentStep) {
                ForEach(Array(steps.enumerated()), id: \.offset) { index, step in
                    VStack(spacing: 16) {
                        Image(systemName: step.systemImage)
                            .font(.system(size: 48, weight: .semibold))
                            .foregroundStyle(Color.accentColor)
                        Text(step.title)
                            .font(.title2.bold())
                        Text(step.description)
                            .multilineTextAlignment(.center)
                            .foregroundColor(.secondary)

                        if let urlString = step.settingsURL, let url = URL(string: urlString) {
                            Button("Open in Settings") {
                                NSWorkspace.shared.open(url)
                            }
                        } else if index == steps.count - 1 {
                            Button("Open Settings") {
                                showSettingsWindow()
                            }
                        }
                    }
                    .padding()
                    .tag(index)
                }
            }
            // .tabViewStyle(.page(indexDisplayMode: .always)) // Unavailable on macOS
            .frame(width: 420, height: 320)

            HStack {
                Button("Back") {
                    currentStep = max(currentStep - 1, 0)
                }
                .disabled(currentStep == 0)

                Spacer()

                Button(currentStep == steps.count - 1 ? "Finish" : "Next") {
                    if currentStep < steps.count - 1 {
                        currentStep += 1
                    } else {
                        completeOnboarding()
                    }
                }
                .keyboardShortcut(.defaultAction)
            }
            .frame(maxWidth: .infinity)
            .padding(.horizontal)
        }
        .padding()
        .frame(width: 460, height: 420)
    }

    private func completeOnboarding() {
        hasCompletedOnboarding = true
        showOnboarding = false
        showSettingsWindow()
    }

    private func showSettingsWindow() {
        // Triggers the SwiftUI Settings scene (Preferences/Settings window)
        NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
    }
}
