import SwiftUI

private enum AiConfigMainTab: String, CaseIterable, Identifiable {
    case status = "状态"
    case models = "模型"
    case prompts = "提示词"
    var id: String { rawValue }
}

private let capabilityOrder: [(id: String, label: String)] = [
    ("chat", "对话"),
    ("vision", "视觉"),
    ("realtimeVoice", "实时语音"),
    ("realtimeVision", "屏幕实时"),
]

private let promptOrder: [(key: String, label: String)] = [
    ("pdfAsk", "PDF"),
    ("videoAsk", "视频"),
    ("audioAsk", "音频"),
    ("imageRegion", "涂鸦截图"),
    ("voiceCall", "语音通话"),
    ("screenShare", "屏幕共享"),
]

struct AiPairView: View {
    @State private var mainTab: AiConfigMainTab = .status
    @State private var modelTab = "chat"
    @State private var promptTab = "pdfAsk"
    @State private var status = "尚未配对"
    @State private var busy = false
    @State private var error: String?
    @State private var showScanner = false
    @State private var lastSynced: String?
    @State private var cached: AiRuntimeConfig?

    var body: some View {
        VStack(spacing: 0) {
            Picker("", selection: $mainTab) {
                ForEach(AiConfigMainTab.allCases) { tab in
                    Text(tab.rawValue).tag(tab)
                }
            }
            .pickerStyle(.segmented)
            .padding()

            Form {
                switch mainTab {
                case .status:
                    statusSection
                case .models:
                    modelsSection
                case .prompts:
                    promptsSection
                }
            }
        }
        .navigationTitle("AI 配置")
        .sheet(isPresented: $showScanner) {
            QRScannerView { code in
                Task { await pair(with: code) }
            }
        }
        .onAppear {
            cached = AiConfigStore.loadConfig()
            refreshStatus()
        }
    }

    @ViewBuilder
    private var statusSection: some View {
        Section("配对状态") {
            LabeledContent("配对", value: AiConfigStore.isPaired ? "已配对" : "未配对")
            if let base = AiConfigStore.shareBaseURL {
                LabeledContent("电脑地址", value: base)
            }
            if let at = AiConfigStore.cachedUpdatedAt {
                LabeledContent("配置时间", value: at)
            }
            if let profile = cached?.profile {
                LabeledContent("预设", value: profileLabel(profile))
            }
            if let lastSynced {
                LabeledContent("最近同步", value: lastSynced)
            }
            Text(status)
                .font(.footnote)
                .foregroundStyle(.secondary)
        }

        Section("操作") {
            Button {
                showScanner = true
            } label: {
                Label("扫码配对 AI 配置", systemImage: "qrcode.viewfinder")
            }
            .disabled(busy)

            Button("立即同步") {
                Task { await syncNow() }
            }
            .disabled(busy || !AiConfigStore.isPaired)

            Button("清除本机 AI 配置", role: .destructive) {
                AiConfigStore.clearConfig()
                AiConfigStore.clearSession()
                cached = nil
                status = "已清除本地配置与配对"
                lastSynced = nil
            }
        }

        if let error {
            Section {
                Text(error).foregroundStyle(.red)
            }
        }
    }

    @ViewBuilder
    private var modelsSection: some View {
        if let cfg = cached {
            Section {
                Picker("能力", selection: $modelTab) {
                    ForEach(capabilityOrder, id: \.id) { item in
                        Text(item.label).tag(item.id)
                    }
                }
                .pickerStyle(.segmented)
            }

            if let ep = cfg.endpoint(for: modelTab) ?? cfg.endpoints.first(where: { $0.capability == modelTab }) {
                Section(capabilityOrder.first(where: { $0.id == modelTab })?.label ?? modelTab) {
                    LabeledContent("启用", value: ep.enabled ? "是" : "否")
                    LabeledContent("Base URL", value: ep.baseUrl)
                    LabeledContent("模型", value: ep.model)
                    LabeledContent("Provider", value: ep.provider)
                    LabeledContent("API Key", value: ep.apiKey.isEmpty ? "未同步" : "已缓存 ·•••\(String(ep.apiKey.suffix(4)))")
                }
            } else {
                Section {
                    Text("电脑尚未配置该能力，请在 PC「AI settings → 模型配置」中填写后重新同步。")
                        .font(.footnote)
                        .foregroundStyle(.secondary)
                }
            }

            Section("功能开关") {
                LabeledContent("PDF 圈选", value: cfg.features.pdfChat ? "开" : "关")
                LabeledContent("视频片段", value: cfg.features.videoRegionAsk ? "开" : "关")
                LabeledContent("音频片段", value: cfg.features.audioClipAsk ? "开" : "关")
                LabeledContent("语音消息", value: cfg.features.voiceMessage ? "开" : "关")
                LabeledContent("实时语音", value: cfg.features.realtimeVoiceCall ? "开" : "关")
                LabeledContent("屏幕共享", value: cfg.features.realtimeScreenShare ? "开" : "关")
            }
        } else {
            Section {
                Text("暂无缓存配置。请先扫码配对或从电脑同步。")
                    .foregroundStyle(.secondary)
            }
        }
    }

    @ViewBuilder
    private var promptsSection: some View {
        if let cfg = cached {
            Section {
                Picker("场景", selection: $promptTab) {
                    ForEach(promptOrder, id: \.key) { item in
                        Text(item.label).tag(item.key)
                    }
                }
                .pickerStyle(.segmented)
            }
            Section(promptOrder.first(where: { $0.key == promptTab })?.label ?? "提示词") {
                Text(promptText(cfg.prompts, key: promptTab))
                    .font(.body)
                    .textSelection(.enabled)
            }
        } else {
            Section {
                Text("暂无提示词缓存。").foregroundStyle(.secondary)
            }
        }
    }

    private func profileLabel(_ p: String) -> String {
        switch p {
        case "domestic-volc": return "火山方舟"
        case "openai": return "OpenAI 兼容"
        default: return p
        }
    }

    private func promptText(_ p: AiPrompts, key: String) -> String {
        switch key {
        case "pdfAsk": return p.pdfAsk
        case "videoAsk": return p.videoAsk
        case "audioAsk": return p.audioAsk
        case "imageRegion": return p.imageRegion.isEmpty ? "（空）" : p.imageRegion
        case "voiceCall": return p.voiceCall.isEmpty ? "（空）" : p.voiceCall
        case "screenShare": return p.screenShare.isEmpty ? "（空）" : p.screenShare
        default: return ""
        }
    }

    private func refreshStatus() {
        if AiConfigStore.isPaired {
            status = cached == nil
                ? "已配对，尚未拉取配置"
                : "已配对，可离线使用多模型缓存"
        } else {
            status = "请扫电脑「AI settings → 分享与高级」中的配对二维码"
        }
    }

    @MainActor
    private func pair(with code: String) async {
        busy = true
        error = nil
        defer { busy = false }
        guard let payload = AiConfigClient.parsePairPayload(code) else {
            error = "无法识别的配对码（需要 studydeck-ai:1?...）"
            return
        }
        do {
            try await AiConfigClient.pair(payload: payload)
            cached = AiConfigStore.loadConfig()
            lastSynced = Date().formatted(date: .omitted, time: .standard)
            status = "配对成功，多模型配置已加密同步到 Keychain"
            refreshStatus()
        } catch {
            self.error = error.localizedDescription
        }
    }

    @MainActor
    private func syncNow() async {
        busy = true
        error = nil
        defer { busy = false }
        do {
            let cfg = try await AiConfigClient.syncFromPC(force: false)
            cached = cfg
            lastSynced = Date().formatted(date: .omitted, time: .standard)
            let n = cfg.endpoints.filter(\.enabled).count
            status = "已同步 · \(cfg.profile) · \(n) 个能力 · \(cfg.updatedAt)"
        } catch {
            self.error = error.localizedDescription
        }
    }
}
