import SwiftUI

/// Neutrale meta-chip volgens proat-designsysteem (geen teal).
struct ProatMetaChip: View {
    let systemImage: String
    let text: String

    var body: some View {
        HStack(spacing: ProatSpacing.xs / 2) {
            Image(systemName: systemImage)
                .font(.system(size: 10))
            Text(text)
                .font(ProatFont.klein)
        }
        .foregroundColor(.proatText2)
        .padding(.horizontal, ProatSpacing.xs - 2)
        .padding(.vertical, 2)
        .background(Capsule().fill(Color.proatBgRaised))
        .overlay(
            Capsule().stroke(Color.proatBorder, lineWidth: 0.5)
        )
    }
}

struct VoiceInkButton: View {
    let title: String
    let action: () -> Void
    var isDisabled: Bool = false

    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.system(size: 14, weight: .semibold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, ProatSpacing.s)
                .background(
                    RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                        .fill(LinearGradient.proatTeal)
                        .opacity(isDisabled ? 0.5 : 1)
                )
        }
        .buttonStyle(.plain)
        .disabled(isDisabled)
    }
}

struct PowerModeEmptyStateView: View {
    let action: () -> Void

    var body: some View {
        VStack(spacing: ProatSpacing.m) {
            Image(systemName: "bolt.circle.fill")
                .font(.system(size: 48))
                .foregroundColor(.proatText3)

            Text("Nog geen Power Modes")
                .font(ProatFont.titel)
                .foregroundColor(.proatText1)

            Text("Voeg aangepaste Power Modes toe voor verschillende contexten")
                .font(ProatFont.body)
                .foregroundColor(.proatText2)
                .multilineTextAlignment(.center)

            VoiceInkButton(
                title: "Nieuwe Power Mode toevoegen",
                action: action
            )
            .frame(maxWidth: 250)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

struct PowerModeConfigurationsGrid: View {
    @ObservedObject var powerModeManager: PowerModeManager
    let onEditConfig: (PowerModeConfig) -> Void
    @EnvironmentObject var enhancementService: AIEnhancementService
    
    var body: some View {
        LazyVStack(spacing: 12) {
            ForEach($powerModeManager.configurations) { $config in
                ConfigurationRow(
                    config: $config,
                    isEditing: false,
                    powerModeManager: powerModeManager,
                    onEditConfig: onEditConfig
                )
            }
        }
    }
}

/// Small, consistent icon-only add button used across Power Mode configuration rows.
struct AddIconButton: View {
    let helpText: String
    var isDisabled: Bool = false
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            Image(systemName: "plus.circle.fill")
                .font(.system(size: 18))
                .symbolRenderingMode(.hierarchical)
                .foregroundStyle(Color.proatTeal)
        }
        .buttonStyle(.plain)
        .help(helpText)
        .accessibilityLabel(helpText)
        .disabled(isDisabled)
    }
}

struct ConfigurationRow: View {
    @Binding var config: PowerModeConfig
    let isEditing: Bool
    let powerModeManager: PowerModeManager
    let onEditConfig: (PowerModeConfig) -> Void
    @EnvironmentObject var enhancementService: AIEnhancementService
    @EnvironmentObject var transcriptionModelManager: TranscriptionModelManager
    @State private var isHovering = false
    
    private let maxAppIconsToShow = 5
    
    private var selectedPrompt: CustomPrompt? {
        guard let promptId = config.selectedPrompt,
              let uuid = UUID(uuidString: promptId) else { return nil }
        return enhancementService.allPrompts.first { $0.id == uuid }
    }
    
    private var selectedModel: String? {
        if let modelName = config.selectedTranscriptionModelName,
           let model = transcriptionModelManager.allAvailableModels.first(where: { $0.name == modelName }) {
            return model.displayName
        }
        return "Standaard"
    }

    private var selectedLanguage: String? {
        if let langCode = config.selectedLanguage {
            if langCode == "auto" { return "Automatisch" }
            if langCode == "en" { return "Engels" }
            
            if let modelName = config.selectedTranscriptionModelName,
               let model = transcriptionModelManager.allAvailableModels.first(where: { $0.name == modelName }),
               let langName = TranscriptionLanguageSupport.languages(for: model)[langCode] {
                return langName
            }
            return langCode.uppercased()
        }
        return "Standaard"
    }
    
    private var appCount: Int { return config.appConfigs?.count ?? 0 }
    private var websiteCount: Int { return config.urlConfigs?.count ?? 0 }
    
    private var websiteText: String {
        if websiteCount == 0 { return "" }
        return websiteCount == 1 ? "1 website" : "\(websiteCount) websites"
    }

    private var appText: String {
        if appCount == 0 { return "" }
        return appCount == 1 ? "1 app" : "\(appCount) apps"
    }
    
    private var extraAppsCount: Int {
        return max(0, appCount - maxAppIconsToShow)
    }
    
    private var visibleAppConfigs: [AppConfig] {
        return Array(config.appConfigs?.prefix(maxAppIconsToShow) ?? [])
    }
    
    var body: some View {
        VStack(spacing: 0) {
            HStack(spacing: ProatSpacing.s) {
                ZStack {
                    Circle()
                        .fill(Color.proatBgSunken)
                        .frame(width: 40, height: 40)

                    Text(config.emoji)
                        .font(.system(size: 20))
                }

                VStack(alignment: .leading, spacing: 3) {
                    HStack(spacing: ProatSpacing.xs - 2) {
                        Text(config.name)
                            .font(ProatFont.sectie)
                            .foregroundColor(.proatText1)

                        if config.isDefault {
                            Text("Standaard")
                                .font(.system(size: 11, weight: .semibold))
                                .padding(.horizontal, ProatSpacing.xs - 2)
                                .padding(.vertical, 2)
                                .background(Capsule().fill(LinearGradient.proatTeal))
                                .foregroundColor(.white)
                        }
                    }

                    HStack(spacing: ProatSpacing.s) {
                        if appCount > 0 {
                            HStack(spacing: ProatSpacing.xs / 2) {
                                Image(systemName: "app.fill")
                                    .font(.system(size: 10))
                                Text(appText)
                                    .font(ProatFont.klein)
                            }
                        }

                        if websiteCount > 0 {
                            HStack(spacing: ProatSpacing.xs / 2) {
                                Image(systemName: "globe")
                                    .font(.system(size: 10))
                                Text(websiteText)
                                    .font(ProatFont.klein)
                            }
                        }
                    }
                    .padding(.top, 2)
                    .foregroundColor(.proatText2)
                }

                Spacer()

                Toggle("", isOn: $config.isEnabled)
                    .toggleStyle(SwitchToggleStyle(tint: .proatTeal))
                    .labelsHidden()
                    .onChange(of: config.isEnabled) { _, _ in
                        powerModeManager.updateConfiguration(config)
                    }
            }
            .padding(.vertical, ProatSpacing.s)
            .padding(.horizontal, ProatSpacing.m - 2)
            
            if selectedModel != nil || selectedLanguage != nil || config.isAIEnhancementEnabled || config.autoSendKey.isEnabled {
                Divider()

                HStack(spacing: ProatSpacing.xs) {
                    if let model = selectedModel, model != "Standaard" {
                        ProatMetaChip(systemImage: "waveform", text: model)
                    }

                    if let language = selectedLanguage, language != "Standaard" {
                        ProatMetaChip(systemImage: "globe", text: language)
                    }

                    if config.isAIEnhancementEnabled, let modelName = config.selectedAIModel, !modelName.isEmpty {
                        ProatMetaChip(
                            systemImage: "cpu",
                            text: modelName.count > 20 ? String(modelName.prefix(18)) + "..." : modelName
                        )
                    }

                    if config.autoSendKey.isEnabled {
                        ProatMetaChip(systemImage: "keyboard", text: config.autoSendKey.displayName)
                    }
                    if config.isAIEnhancementEnabled {
                        if config.useScreenCapture {
                            ProatMetaChip(systemImage: "camera.viewfinder", text: "Contextbewustzijn")
                        }

                        HStack(spacing: ProatSpacing.xs / 2) {
                            Image(systemName: "sparkles")
                                .font(.system(size: 10))
                            Text(selectedPrompt?.title ?? "AI")
                                .font(ProatFont.klein)
                        }
                        .padding(.horizontal, ProatSpacing.xs - 2)
                        .padding(.vertical, 2)
                        .background(Capsule()
                            .fill(Color.proatTealTint))
                        .foregroundColor(.proatTeal)
                    }

                    Spacer()
                }

                .padding(.vertical, ProatSpacing.xs - 2)
                .padding(.horizontal, ProatSpacing.m)
                .background(Color.proatBgSunken)
            }
    }
    .clipShape(RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous))
    .background(ProatModelCardBackground(isSelected: isEditing))
    .opacity(config.isEnabled ? 1.0 : 0.5)

    .onHover { hovering in
        withAnimation(.easeInOut(duration: 0.15)) {
            isHovering = hovering
        }
    }
    .onTapGesture(count: 2) {
        onEditConfig(config)
    }
    .contextMenu {
        Button(action: {
            onEditConfig(config)
        }) {
            Label("Bewerken", systemImage: "pencil")
        }
        Button(role: .destructive, action: {
            let alert = NSAlert()
            alert.messageText = "Power Mode verwijderen?"
            alert.informativeText = "Weet je zeker dat je de Power Mode '\(config.name)' wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt."
            alert.alertStyle = .warning
            alert.addButton(withTitle: "Verwijderen")
            alert.addButton(withTitle: "Annuleren")
            alert.buttons[0].hasDestructiveAction = true
            
            if alert.runModal() == .alertFirstButtonReturn {
                powerModeManager.removeConfiguration(with: config.id)
            }
        }) {
            Label("Verwijderen", systemImage: "trash")
        }
    }
    }
    
    private var isSelected: Bool {
        return isEditing
    }
}

struct PowerModeAppIcon: View {
    let bundleId: String
    
    var body: some View {
        if let appUrl = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleId) {
            Image(nsImage: NSWorkspace.shared.icon(forFile: appUrl.path))
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 20, height: 20)
        } else {
            Image(systemName: "app.fill")
                .font(.system(size: 14))
                .foregroundColor(.proatText3)
                .frame(width: 20, height: 20)
        }
    }
}

struct AppGridItem: View {
    let app: (url: URL, name: String, bundleId: String, icon: NSImage)
    let isSelected: Bool
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            VStack(spacing: 8) {
                Image(nsImage: app.icon)
                    .resizable()
                    .frame(width: 40, height: 40)
                    .cornerRadius(8)
                    .shadow(color: Color(NSColor.shadowColor).opacity(0.1), radius: 2, x: 0, y: 1)
                Text(app.name)
                    .font(.system(size: 10))
                    .foregroundColor(.proatText1)
                    .lineLimit(2)
                    .multilineTextAlignment(.center)
                    .frame(height: 28)
            }
            .frame(width: 80, height: 80)
            .padding(ProatSpacing.xs - 2)
            .background(
                RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                    .fill(isSelected ? Color.proatTealTint : Color.clear)
            )
            .overlay(
                RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous)
                    .stroke(isSelected ? Color.proatTeal : Color.clear, lineWidth: 1)
            )
        }
        .buttonStyle(.plain)
    }
}
