import SwiftUI

struct SettingsView: View {
    @StateObject private var modelManager = ModelManager.shared
    @StateObject private var appState = AppState.shared
    
    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                Text("Dictation Settings")
                    .font(.title2)
                    .fontWeight(.semibold)
                
                Divider()
                
                GroupBox(label: Label("Dictation", systemImage: "mic.fill")) {
                    VStack(alignment: .leading, spacing: 12) {
                        HStack {
                            Image(systemName: "keyboard")
                                .foregroundColor(.blue)
                            Text("Press Dictation key (F5) to start/stop recording")
                                .font(.subheadline)
                        }
                        
                        Text("The app takes over your system dictation key when running. Transcriptions are automatically pasted into the active text field.")
                            .font(.caption)
                            .foregroundColor(.secondary)
                            .padding(.top, 4)
                        
                        Divider()
                            .padding(.vertical, 4)
                        
                        VStack(alignment: .leading, spacing: 4) {
                            Toggle("Restore clipboard after pasting", isOn: Binding(
                                get: { appState.restoreClipboard },
                                set: { _ in appState.toggleClipboardRestore() }
                            ))
                            .toggleStyle(.switch)
                            
                            Text("When ON: saves your clipboard, pastes transcription, then restores your clipboard")
                                .font(.caption2)
                                .foregroundColor(.secondary)
                                .padding(.leading, 4)
                        }
                    }
                    .padding(8)
                }
                
                Divider()
                
                GroupBox(label: Label("Appearance", systemImage: "eye")) {
                    VStack(alignment: .leading, spacing: 12) {
                        VStack(alignment: .leading, spacing: 4) {
                            Toggle("Show icon in Dock", isOn: Binding(
                                get: { appState.showInDock },
                                set: { _ in appState.toggleDockIcon() }
                            ))
                            .toggleStyle(.switch)
                            
                            Text("When OFF: App runs in background. Reopen from Applications folder to show window again.")
                                .font(.caption2)
                                .foregroundColor(.secondary)
                                .padding(.leading, 4)
                        }
                    }
                    .padding(8)
                }
            
            Divider()
            
            GroupBox(label: Label("Model Selection", systemImage: "waveform")) {
                VStack(alignment: .leading, spacing: 8) {
                    Picker("Model Version:", selection: $modelManager.selectedModelVersion) {
                        ForEach(ParakeetModelVersion.allCases) { version in
                            Text(version.displayName).tag(version)
                        }
                    }
                    .pickerStyle(.menu)
                    .onChange(of: modelManager.selectedModelVersion) { _, _ in
                        modelManager.saveModelPreference()
                        modelManager.modelState = .notDownloaded
                    }
                    
                    Text("Model will download on first use")
                        .font(.caption2)
                        .foregroundColor(.secondary)
                }
                .padding(8)
            }
            
            GroupBox(label: Label("Model Status", systemImage: "cpu")) {
                VStack(alignment: .leading, spacing: 8) {
                    HStack {
                        Text("Status:")
                            .fontWeight(.medium)
                        Spacer()
                        statusBadge
                    }
                    
                    if modelManager.modelState == .downloading {
                        VStack(alignment: .leading, spacing: 6) {
                            if let message = modelManager.errorMessage {
                                Text(message)
                                    .font(.caption)
                                    .foregroundColor(.blue)
                            }
                            ProgressView(value: modelManager.downloadProgress) {
                                Text("Downloading model files...")
                                    .font(.caption)
                            }
                        }
                        .padding(.top, 4)
                    } else if modelManager.modelState == .error {
                    if let error = modelManager.errorMessage {
                        Text(error)
                            .font(.caption)
                            .foregroundColor(.red)
                        }
                    }
                }
                .padding(8)
            }
            
            GroupBox(label: Label("Model Information", systemImage: "info.circle")) {
                VStack(alignment: .leading, spacing: 6) {
                    infoRow(label: "Model", value: "Parakeet TDT 0.6B \(modelManager.selectedModelVersion.asrVersion)")
                    infoRow(label: "Language", value: modelManager.selectedModelVersion.language)
                    infoRow(label: "Size", value: modelManager.selectedModelVersion.size)
                    infoRow(label: "Runtime", value: "Apple Neural Engine")
                }
                .padding(8)
            }
            
                Spacer(minLength: 20)
                
                Text("Change model version anytime • Models download automatically when needed")
                    .font(.caption)
                    .foregroundColor(.secondary)
                    .multilineTextAlignment(.center)
                
                // Version info
                VStack(spacing: 4) {
                    Text("lowercase \(appVersion)")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    Text("Build \(buildNumber)")
                        .font(.caption2)
                        .foregroundColor(.secondary.opacity(0.7))
                    Text("Max Awad © 2025. All rights reserved.")
                        .font(.caption2)
                        .foregroundColor(.secondary.opacity(0.7))
                }
                .multilineTextAlignment(.center)
                .padding(.top, 12)
                .padding(.bottom, 20)
            }
            .padding()
        }
        .frame(width: 500, height: 600)
    }
    
    private var appVersion: String {
        Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"
    }
    
    private var buildNumber: String {
        Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "Unknown"
    }
    
    private var statusBadge: some View {
        HStack {
            Circle()
                .fill(statusColor)
                .frame(width: 8, height: 8)
            Text(statusText)
                .font(.caption)
                .fontWeight(.medium)
        }
        .padding(.horizontal, 8)
        .padding(.vertical, 4)
        .background(statusColor.opacity(0.2))
        .cornerRadius(8)
    }
    
    private var statusColor: Color {
        switch modelManager.modelState {
        case .notDownloaded:
            return .orange
        case .downloading:
            return .blue
        case .ready:
            return .green
        case .error:
            return .red
        }
    }
    
    private var statusText: String {
        switch modelManager.modelState {
        case .notDownloaded:
            return "Not Downloaded"
        case .downloading:
            return "Downloading..."
        case .ready:
            return "Ready"
        case .error:
            return "Error"
        }
    }
    
    private func infoRow(label: String, value: String) -> some View {
        HStack {
            Text(label + ":")
                .foregroundColor(.secondary)
            Spacer()
            Text(value)
                .fontWeight(.medium)
        }
        .font(.caption)
    }
}

