//
//  SettingsView.swift
//  aoqdemo
//

import SwiftUI

// MARK: - AppServer 地址管理

enum AppServerConfig {
    /// AppServer 服务器基础地址（不含 path）。
    static let defaultBaseURL = "xxx"

    /// 预设的 AppServer 地址列表，供下拉菜单选择。
    static let presetBaseURLs: [String] = []

    /// allocate 接口路径。
    static let allocatePath = "/api/v1/allocate"

    static let userDefaultsKey = "appserver_base_url"

    /// 当前生效的 baseURL：优先读本地存储，无值返回默认。
    static var currentBaseURL: String {
        let saved = UserDefaults.standard.string(forKey: userDefaultsKey) ?? ""
        return saved.isEmpty ? defaultBaseURL : saved
    }

    /// 当前生效的完整 allocate URL（展示与实际请求都用它）。
    static var currentAllocateURL: String {
        allocateURL(from: currentBaseURL)
    }

    /// 保存 baseURL。空串或等于默认值时清除本地存储。
    static func save(_ baseURL: String) {
        if baseURL.isEmpty || baseURL == defaultBaseURL {
            UserDefaults.standard.removeObject(forKey: userDefaultsKey)
        } else {
            UserDefaults.standard.set(baseURL, forKey: userDefaultsKey)
        }
    }

    /// 拼接出完整的 allocate URL，自动去掉 baseURL 末尾多余的斜杠。
    static func allocateURL(from baseURL: String) -> String {
        let trimmed = baseURL.hasSuffix("/") ? String(baseURL.dropLast()) : baseURL
        return trimmed + allocatePath
    }
}

// MARK: - 会话配置（session.update）

enum SessionConfig {
    static let defaultVoice = "Tina"

    /// 预设音色列表（通用音色，覆盖男女声）。
    static let presetVoices: [String] = [
        "Tina", "Serena", "Cindy", "Ethan", "Ryan"
    ]

    static let voiceUserDefaultsKey = "session_voice"

    /// 当前生效的音色：优先读本地存储，无值返回默认。
    static var currentVoice: String {
        let saved = UserDefaults.standard.string(forKey: voiceUserDefaultsKey)?
            .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
        return saved.isEmpty ? defaultVoice : saved
    }

    /// 保存音色。空串或等于默认值时清除本地存储。
    static func saveVoice(_ voice: String) {
        let trimmed = voice.trimmingCharacters(in: .whitespacesAndNewlines)
        if trimmed.isEmpty || trimmed == defaultVoice {
            UserDefaults.standard.removeObject(forKey: voiceUserDefaultsKey)
        } else {
            UserDefaults.standard.set(trimmed, forKey: voiceUserDefaultsKey)
        }
    }
}

// MARK: - SettingsView

struct SettingsView: View {
    @State private var appServerURL: String = ""
    @State private var selectedPreset: String = ""
    @State private var showSaved: Bool = false
    @State private var selectedVoice: String = SessionConfig.defaultVoice

    var body: some View {
        Form {
            Section {
                VStack(alignment: .leading, spacing: 8) {
                    Text("AppServer 服务器地址")
                        .font(.headline)
                    Text("可通过下拉选择预设地址，也可手动输入自定义地址。不要带 /api/v1/allocate。")
                        .font(.caption)
                        .foregroundStyle(.secondary)

                    Picker("预设地址", selection: $selectedPreset) {
                        ForEach(AppServerConfig.presetBaseURLs, id: \.self) { url in
                            Text(url).tag(url)
                        }
                        Text("自定义").tag("")
                    }
                    .pickerStyle(.menu)
                    .onChange(of: selectedPreset) { newValue in
                        if !newValue.isEmpty {
                            appServerURL = newValue
                        }
                    }

                    TextField("输入 AppServer 服务器地址", text: $appServerURL)
                        .textFieldStyle(.roundedBorder)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)
                        .onChange(of: appServerURL) { newValue in
                            if AppServerConfig.presetBaseURLs.contains(newValue) {
                                selectedPreset = newValue
                            } else {
                                selectedPreset = ""
                            }
                        }

                    HStack(spacing: 12) {
                        Button("保存") {
                            AppServerConfig.save(appServerURL)
                            appServerURL = AppServerConfig.currentBaseURL
                            syncPresetSelection()
                            showSaved = true
                            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                showSaved = false
                            }
                        }
                        .buttonStyle(.borderedProminent)

                        Button("恢复默认") {
                            AppServerConfig.save("")
                            appServerURL = AppServerConfig.defaultBaseURL
                            syncPresetSelection()
                            showSaved = true
                            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                showSaved = false
                            }
                        }

                        if showSaved {
                            Label("已保存", systemImage: "checkmark.circle.fill")
                                .foregroundStyle(.green)
                                .font(.caption)
                                .transition(.opacity)
                        }
                    }
                    .animation(.easeInOut, value: showSaved)
                }
                .padding(.vertical, 4)
            } header: {
                Label("服务器配置", systemImage: "server.rack")
            }

            Section {
                VStack(alignment: .leading, spacing: 8) {
                    Text("会话音色")
                        .font(.headline)
                    Text("用于 session.update 中的 voice 字段，对所有走 AI 通话/视频理解/打电话的功能生效。通话中修改需挂断后重新拨打。")
                        .font(.caption)
                        .foregroundStyle(.secondary)

                    HStack(spacing: 12) {
                        Menu {
                            ForEach(SessionConfig.presetVoices, id: \.self) { name in
                                Button(name) {
                                    selectedVoice = name
                                    SessionConfig.saveVoice(name)
                                }
                            }
                        } label: {
                            HStack(spacing: 6) {
                                Text(selectedVoice).font(.subheadline)
                                Image(systemName: "chevron.down").font(.caption2)
                            }
                            .foregroundStyle(Color.blue)
                            .padding(.horizontal, 12)
                            .frame(height: 32)
                            .background(Color(uiColor: .tertiarySystemFill))
                            .clipShape(RoundedRectangle(cornerRadius: 6))
                        }

                        Button("恢复默认") {
                            selectedVoice = SessionConfig.defaultVoice
                            SessionConfig.saveVoice("")
                        }
                        .font(.subheadline)

                        Spacer()
                    }
                }
                .padding(.vertical, 4)
            } header: {
                Label("会话配置", systemImage: "waveform")
            }
        }
        .background(Color(uiColor: .systemGroupedBackground))
        .navigationTitle("设置")
        .navigationBarTitleDisplayMode(.inline)
        .onAppear {
            appServerURL = AppServerConfig.currentBaseURL
            syncPresetSelection()
            selectedVoice = SessionConfig.currentVoice
        }
    }

    private func syncPresetSelection() {
        if AppServerConfig.presetBaseURLs.contains(appServerURL) {
            selectedPreset = appServerURL
        } else {
            selectedPreset = ""
        }
    }
}

#Preview {
    NavigationStack {
        SettingsView()
    }
}
