import SwiftUI
import SwiftData
import KeyboardShortcuts
import OSLog

// ViewType enum with all cases
// Note: rawValue is the internal/routing identifier (English). User-facing label
// is `displayName` (Dutch with subtle Achterhoeks flavor where it doesn't
// confuse functionality).
enum ViewType: String, CaseIterable, Identifiable {
    case metrics = "Dashboard"
    case transcribeAudio = "Transcribe Audio"
    case history = "History"
    case models = "AI Models"
    case enhancement = "Enhancement"
    case powerMode = "Power Mode"
    case permissions = "Permissions"
    case audioInput = "Audio Input"
    case dictionary = "Dictionary"
    case settings = "Settings"
    case license = "Proat Pro"

    var id: String { rawValue }

    var displayName: String {
        switch self {
        case .metrics: return "Start"
        case .transcribeAudio: return "Audio omzetten"
        case .history: return "Historie"
        case .models: return "Stem & model"
        case .enhancement: return "Verfijning"
        case .powerMode: return "Power Mode"
        case .permissions: return "Toestemmingen"
        case .audioInput: return "Audio-ingang"
        case .dictionary: return "Woordenboek"
        case .settings: return "Instellingen"
        case .license: return "Proat Pro"
        }
    }

    var icon: String {
        switch self {
        case .metrics: return "house.fill"
        case .transcribeAudio: return "waveform.circle.fill"
        case .history: return "clock.fill"
        case .models: return "waveform.and.mic"
        case .enhancement: return "wand.and.stars"
        case .powerMode: return "sparkles.square.fill.on.square"
        case .permissions: return "shield.fill"
        case .audioInput: return "mic.fill"
        case .dictionary: return "character.book.closed.fill"
        case .settings: return "gearshape.fill"
        case .license: return "checkmark.seal.fill"
        }
    }
}

struct VisualEffectView: NSViewRepresentable {
    let material: NSVisualEffectView.Material
    let blendingMode: NSVisualEffectView.BlendingMode

    func makeNSView(context: Context) -> NSVisualEffectView {
        let visualEffectView = NSVisualEffectView()
        visualEffectView.material = material
        visualEffectView.blendingMode = blendingMode
        visualEffectView.state = .active
        return visualEffectView
    }

    func updateNSView(_ visualEffectView: NSVisualEffectView, context: Context) {
        visualEffectView.material = material
        visualEffectView.blendingMode = blendingMode
    }
}

struct ContentView: View {
    private let logger = Logger(subsystem: "com.noaber.proat", category: "ContentView")
    @Environment(\.modelContext) private var modelContext
    @Environment(\.colorScheme) private var colorScheme
    @EnvironmentObject private var engine: VoiceInkEngine
    @EnvironmentObject private var whisperModelManager: WhisperModelManager
    @EnvironmentObject private var transcriptionModelManager: TranscriptionModelManager
    @EnvironmentObject private var hotkeyManager: HotkeyManager
    @AppStorage("powerModeUIFlag") private var powerModeUIFlag = false
    @State private var selectedView: ViewType? = .metrics
    let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0"
    @StateObject private var licenseViewModel = LicenseViewModel()

    // IA-consolidatie (Fase 2): exact 5 nav-items, vaste volgorde.
    // Start, Historie, Verfijning, Stem & model, Instellingen.
    // transcribeAudio/powerMode/license/permissions/audioInput/dictionary
    // blijven bestaande ViewType-cases voor deep-link- en menubalk-routing,
    // maar verschijnen niet als eigen zijbalk-rij (ze zijn opgenomen in de
    // samengestelde schermen of worden programmatisch genavigeerd).
    private var visibleViewTypes: [ViewType] {
        [.metrics, .history, .enhancement, .models, .settings]
    }

    var body: some View {
        NavigationSplitView {
            List(selection: $selectedView) {
                Section {
                    // Merk-kop: noaber.ai-logo prominent + functioneel.
                    VStack(alignment: .leading, spacing: ProatSpacing.xs) {
                        HStack(spacing: ProatSpacing.s) {
                            if let appIcon = NSImage(named: "AppIcon") {
                                Image(nsImage: appIcon)
                                    .resizable()
                                    .aspectRatio(contentMode: .fit)
                                    .frame(width: 44, height: 44)
                                    .clipShape(RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous))
                                    .overlay(
                                        RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                                            .stroke(Color.proatTeal.opacity(0.35), lineWidth: 1)
                                    )
                                    .proatShadowRust()
                            }

                            HStack(spacing: 5) {
                                Text("Proat")
                                    .font(.system(size: 20, weight: .bold))
                                    .foregroundStyle(Color.proatText1)

                                if case .licensed = licenseViewModel.licenseState {
                                    Text("PRO")
                                        .font(.system(size: 9, weight: .heavy))
                                        .foregroundStyle(.white)
                                        .padding(.horizontal, 5)
                                        .padding(.vertical, 2)
                                        .background(LinearGradient.proatTeal)
                                        .clipShape(Capsule())
                                }
                            }

                            Spacer(minLength: 0)
                        }

                        HStack(spacing: 5) {
                            Text("door")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundStyle(Color.proatText3)
                            // noaber.ai-wordmark als scherpe tekst (logo is tekst-based).
                            HStack(spacing: 0) {
                                Text("noaber")
                                    .foregroundStyle(Color.proatText1)
                                Text(".ai")
                                    .foregroundStyle(Color.proatTeal)
                            }
                            .font(.system(size: 17, weight: .bold))
                            .accessibilityLabel("noaber.ai")
                            Spacer(minLength: 0)
                        }
                    }
                    .padding(.vertical, ProatSpacing.s)
                }

                ForEach(visibleViewTypes) { viewType in
                    Section {
                        NavigationLink(value: viewType) {
                            SidebarItemView(viewType: viewType)
                        }
                        .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
                        .listRowSeparator(.hidden)
                    }
                }
            }
            .listStyle(.sidebar)
            .navigationTitle("Proat")
            .navigationSplitViewColumnWidth(210)
        } detail: {
            if let selectedView = selectedView {
                detailView(for: selectedView)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .navigationTitle(selectedView.displayName)
            } else {
                Text("Kies een onderdeel")
                    .foregroundColor(.secondary)
            }
        }
        .navigationSplitViewStyle(.balanced)
        .frame(width: 950)
        .frame(minHeight: 730)
        .onAppear {
            logger.notice("ContentView appeared")
        }
        .onDisappear {
            logger.notice("ContentView disappeared")
        }
        .onReceive(NotificationCenter.default.publisher(for: .navigateToDestination)) { notification in
            if let destination = notification.userInfo?["destination"] as? String {
                logger.notice("navigateToDestination received: \(destination, privacy: .public)")
                switch destination {
                case "Settings":
                    selectedView = .settings
                case "AI Models":
                    selectedView = .models
                case "Proat Pro":
                    selectedView = .license
                case "History":
                    selectedView = .history
                case "Permissions":
                    selectedView = .permissions
                case "Enhancement":
                    selectedView = .enhancement
                case "Transcribe Audio":
                    selectedView = .transcribeAudio
                case "Power Mode":
                    selectedView = .powerMode
                default:
                    break
                }
            }
        }
    }
    
    @ViewBuilder
    private func detailView(for viewType: ViewType) -> some View {
        switch viewType {
        case .metrics:
            MetricsView()
        case .models:
            // "Stem & model": modelbeheer + audio-ingang samengesteld.
            StemEnModelView()
        case .enhancement:
            // "Verfijning": AI-verfijning + woordenboek samengesteld.
            VerfijningView()
        case .transcribeAudio:
            AudioTranscribeView()
        case .history:
            InlineHistoryView()
        case .audioInput:
            AudioInputSettingsView()
        case .dictionary:
            DictionarySettingsView(whisperPrompt: whisperModelManager.whisperPrompt)
        case .powerMode:
            PowerModeView()
        case .settings:
            SettingsView()
        case .license:
            LicenseManagementView()
        case .permissions:
            PermissionsView()
        }
    }
}

private struct SidebarItemView: View {
    let viewType: ViewType

    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: viewType.icon)
                .font(.system(size: 18, weight: .medium))
                .frame(width: 24, height: 24)

            Text(viewType.displayName)
                .font(.system(size: 14, weight: .medium))

            Spacer()
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .contentShape(Rectangle())
        .padding(.vertical, 8)
        .padding(.horizontal, 2)
    }
}

