import SwiftUI
import AppKit
import LLMkit

// MARK: - Cloud Model Card View
struct CloudModelCardView: View {
    let model: CloudModel
    let isCurrent: Bool
    var setDefaultAction: () -> Void

    @EnvironmentObject private var transcriptionModelManager: TranscriptionModelManager
    @AppStorage("SelectedLanguage") private var selectedLanguage: String = "en"
    @State private var isExpanded = false
    @State private var apiKey = ""
    @State private var streamingEnabled: Bool

    init(model: CloudModel, isCurrent: Bool, setDefaultAction: @escaping () -> Void) {
        self.model = model
        self.isCurrent = isCurrent
        self.setDefaultAction = setDefaultAction
        let key = "streaming-enabled-\(model.name)"
        _streamingEnabled = State(initialValue: UserDefaults.standard.object(forKey: key) as? Bool ?? true)
    }
    @State private var isVerifying = false
    @State private var verificationStatus: VerificationStatus = .none
    @State private var verificationError: String? = nil
    
    enum VerificationStatus {
        case none, verifying, success, failure
    }
    
    private var isConfigured: Bool {
        return APIKeyManager.shared.hasAPIKey(forProvider: providerKey)
    }
    
    private var providerKey: String {
        CloudProviderRegistry.provider(for: model.provider)?.providerKey ?? model.provider.rawValue
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Main card content
            HStack(alignment: .top, spacing: ProatSpacing.m) {
                VStack(alignment: .leading, spacing: ProatSpacing.xs - 2) {
                    headerSection
                    metadataSection
                    descriptionSection
                }
                .frame(maxWidth: .infinity, alignment: .leading)

                actionSection
            }
            .padding(ProatSpacing.m)

            // Expandable configuration section
            if isExpanded {
                Divider()
                    .padding(.horizontal, ProatSpacing.m)

                configurationSection
                    .padding(ProatSpacing.m)
            }
        }
        .background(ProatModelCardBackground(isSelected: isCurrent))
        .onAppear {
            loadSavedAPIKey()
        }
    }

    private var headerSection: some View {
        HStack(alignment: .firstTextBaseline) {
            Text(model.displayName)
                .font(ProatFont.sectie)
                .foregroundColor(.proatText1)

            if model.supportsStreaming && isConfigured {
                streamingModeBadge
            }

            Spacer()
        }
    }
    
    private var isStreamingOnly: Bool {
        CloudProviderRegistry.provider(for: model.provider)?.isStreamingOnly ?? false
    }

    private var streamingModeBadge: some View {
        Toggle("Realtime", isOn: isStreamingOnly ? .constant(true) : $streamingEnabled)
            .toggleStyle(.switch)
            .controlSize(.mini)
            .font(.system(size: 11, weight: .medium))
            .foregroundColor(.proatText2)
            .disabled(isStreamingOnly)
            .onChange(of: streamingEnabled) { _, newValue in
                if !isStreamingOnly {
                    UserDefaults.standard.set(newValue, forKey: streamingDefaultsKey)
                    ensureCurrentModelLanguageIsStillValid()
                    NotificationCenter.default.post(name: .AppSettingsDidChange, object: nil)
                }
            }
            .help(isStreamingOnly ? "Dit model ondersteunt alleen realtime streaming" : (streamingEnabled ? "Live streaming ingeschakeld — klik om naar batch te wisselen" : "Batchmodus — klik om live streaming in te schakelen"))
    }

    private func ensureCurrentModelLanguageIsStillValid() {
        guard transcriptionModelManager.currentTranscriptionModel?.name == model.name else {
            return
        }

        let compatibleLanguage = TranscriptionLanguageSupport.validLanguageOrFallback(selectedLanguage, for: model)
        if selectedLanguage != compatibleLanguage {
            selectedLanguage = compatibleLanguage
            NotificationCenter.default.post(name: .languageDidChange, object: nil)
        }
    }

    private var metadataSection: some View {
        HStack(spacing: ProatSpacing.s) {
            // Provider
            Label(model.provider.rawValue, systemImage: "cloud")
                .font(ProatFont.klein)
                .foregroundColor(.proatText2)
                .lineLimit(1)

            // Language
            Label(model.language, systemImage: "globe")
                .font(ProatFont.klein)
                .foregroundColor(.proatText2)
                .lineLimit(1)

            // Speed
            HStack(spacing: 3) {
                Text("Snelheid")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(.proatText2)
                progressDotsWithNumber(value: model.speed * 10)
            }
            .lineLimit(1)
            .fixedSize(horizontal: true, vertical: false)

            // Accuracy
            HStack(spacing: 3) {
                Text("Nauwkeurigheid")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(.proatText2)
                progressDotsWithNumber(value: model.accuracy * 10)
            }
            .lineLimit(1)
            .fixedSize(horizontal: true, vertical: false)
        }
        .lineLimit(1)
    }

    private var descriptionSection: some View {
        Text(model.description)
            .font(ProatFont.klein)
            .foregroundColor(.proatText3)
            .lineLimit(2)
            .fixedSize(horizontal: false, vertical: true)
            .padding(.top, ProatSpacing.xs / 2)
    }

    private var actionSection: some View {
        HStack(spacing: ProatSpacing.xs) {
            if isCurrent {
                Text("Standaardmodel")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(.proatTeal)
            } else if isConfigured {
                Button(action: setDefaultAction) {
                    Text("Als standaard instellen")
                        .font(.system(size: 12))
                }
                .buttonStyle(.bordered)
                .controlSize(.small)
            } else {
                Button(action: {
                    withAnimation(.interpolatingSpring(stiffness: 170, damping: 20)) {
                        isExpanded.toggle()
                    }
                }) {
                    ProatPrimaryPillLabel(title: "Configureren", systemImage: "gear")
                }
                .buttonStyle(.plain)
            }

            if isConfigured {
                Menu {
                    Button {
                        clearAPIKey()
                    } label: {
                        Label("API-sleutel verwijderen", systemImage: "trash")
                    }
                } label: {
                    Image(systemName: "ellipsis.circle")
                        .font(.system(size: 14))
                        .foregroundColor(.proatText2)
                }
                .menuStyle(.borderlessButton)
                .menuIndicator(.hidden)
                .frame(width: 20, height: 20)
            }
        }
    }

    private var configurationSection: some View {
        VStack(alignment: .leading, spacing: ProatSpacing.s) {
            Text("API-sleutel instellen")
                .font(ProatFont.sectie)
                .foregroundColor(.proatText1)

            HStack(spacing: ProatSpacing.xs) {
                SecureField("Voer je \(model.provider.rawValue)-API-sleutel in", text: $apiKey)
                    .textFieldStyle(.roundedBorder)
                    .disabled(isVerifying)

                Button(action: verifyAPIKey) {
                    HStack(spacing: ProatSpacing.xs / 2) {
                        if isVerifying {
                            ProgressView()
                                .scaleEffect(0.7)
                                .frame(width: 12, height: 12)
                        } else {
                            Image(systemName: verificationStatus == .success ? "checkmark" : "checkmark.shield")
                                .font(.system(size: 12, weight: .semibold))
                        }
                        Text(isVerifying ? "Verifiëren…" : "Verifiëren")
                            .font(.system(size: 12, weight: .semibold))
                    }
                    .foregroundColor(.white)
                    .padding(.horizontal, ProatSpacing.s)
                    .padding(.vertical, ProatSpacing.xs - 2)
                    .background(
                        Capsule()
                            .fill(verificationStatus == .success
                                  ? AnyShapeStyle(Color.proatOK)
                                  : AnyShapeStyle(LinearGradient.proatTeal))
                    )
                    .proatShadowRust()
                }
                .buttonStyle(.plain)
                .disabled(apiKey.isEmpty || isVerifying)
            }

            if verificationStatus == .failure {
                if let error = verificationError {
                    Text(error)
                        .font(ProatFont.klein)
                        .foregroundColor(.proatError)
                } else {
                    Text("Verificatie mislukt")
                        .font(ProatFont.klein)
                        .foregroundColor(.proatError)
                }
            } else if verificationStatus == .success {
                Text("API-sleutel geverifieerd.")
                    .font(ProatFont.klein)
                    .foregroundColor(.proatOK)
            }
        }
    }
    
    private var streamingDefaultsKey: String {
        "streaming-enabled-\(model.name)"
    }

    private func loadSavedAPIKey() {
        if let savedKey = APIKeyManager.shared.getAPIKey(forProvider: providerKey) {
            apiKey = savedKey
            verificationStatus = .success
        }
    }
    
    private func verifyAPIKey() {
        guard !apiKey.isEmpty else { return }

        isVerifying = true
        verificationStatus = .verifying
        let key = apiKey

        guard let cloudProvider = CloudProviderRegistry.provider(for: model.provider) else {
            isVerifying = false
            verificationStatus = .failure
            verificationError = "Provider wordt niet ondersteund"
            return
        }

        Task {
            let result = await cloudProvider.verifyAPIKey(key)

            await MainActor.run {
                isVerifying = false
                if result.isValid {
                    verificationStatus = .success
                    verificationError = nil
                    APIKeyManager.shared.saveAPIKey(key, forProvider: providerKey)
                    transcriptionModelManager.refreshAllAvailableModels()
                    withAnimation(.easeInOut(duration: 0.3)) {
                        isExpanded = false
                    }
                } else {
                    verificationStatus = .failure
                    verificationError = result.errorMessage
                }
            }
        }
    }
    
    private func clearAPIKey() {
        APIKeyManager.shared.deleteAPIKey(forProvider: providerKey)
        apiKey = ""
        verificationStatus = .none
        verificationError = nil

        if isCurrent {
            transcriptionModelManager.clearCurrentTranscriptionModel()
        }

        transcriptionModelManager.refreshAllAvailableModels()

        withAnimation(.easeInOut(duration: 0.3)) {
            isExpanded = false
        }
    }
}
