import SwiftUI
import AoqClientSdk

struct LinkAPIView: View {
    @StateObject private var mgr = AoqEngineManager.shared

    // Connection config inputs
    @State private var workDir: String = NSTemporaryDirectory()
    @State private var extras: String = ""
    @State private var token: String = ""
    @State private var sid: String = ""
    @State private var certificate: String = ""
    /* relay 接入点列表的 JSON 表示，默认单个 127.0.0.1:8006 */
    @State private var relayEndpointsJSON: String = "[\n  {\n    \"endpoint\" : \"127.0.0.1\",\n    \"port\" : 8006\n  }\n]"
    @State private var workspaceIdHash: String = ""

    // DataMsg config
    @State private var datamsgText: String = "Hello"

    var body: some View {
        ScrollView {
            VStack(spacing: 16) {
                statusCard
                AppServerAllocateSection(
                    token: $token,
                    sid: $sid,
                    certificate: $certificate,
                    relayEndpointsJSON: $relayEndpointsJSON,
                    workspaceIdHash: $workspaceIdHash
                )
                connectCard
                datamsgCard
                logCard
            }
            .padding(16)
        }
        .background(Color(uiColor: .systemGroupedBackground))
        .navigationTitle("链接API")
        .navigationBarTitleDisplayMode(.inline)
    }

    // MARK: - Status

    private var statusCard: some View {
        CardSection(title: "引擎状态") {
            StatusRow(title: "SDK 版本", value: mgr.sdkVersion.isEmpty ? "-" : mgr.sdkVersion)
            StatusRow(title: "引擎实例", value: mgr.isEngineCreated ? "已创建" : "未创建",
                      color: mgr.isEngineCreated ? .green : .secondary)
            StatusRow(title: "连接状态", value: mgr.isConnected ? "已连接" : "未连接",
                      color: mgr.isConnected ? .green : .secondary)
            StatusRow(title: "最近错误", value: mgr.lastError.isEmpty ? "-" : mgr.lastError,
                      color: mgr.lastError.isEmpty ? .secondary : .red)
        }
    }

    // MARK: - Connect

    private var connectCard: some View {
        CardSection(title: "连接配置") {
            LabeledInput(label: "Token", text: $token, placeholder: "输入 Token")
            LabeledInput(label: "SID", text: $sid, placeholder: "输入 SID")
            LabeledInput(label: "Certificate", text: $certificate, placeholder: "输入 Certificate")
            relayEndpointsEditor
            LabeledInput(label: "WsIdHash", text: $workspaceIdHash, placeholder: "工作空间哈希 ID")
            LabeledInput(label: "WorkDir", text: $workDir, placeholder: "工作目录")

            HStack(spacing: 12) {
                Button("创建引擎") {
                    mgr.createEngine(workDir: workDir, enableDumpAudio: false, extras: extras)
                }
                .buttonStyle(.bordered)
                .disabled(mgr.isEngineCreated)

                Button("销毁引擎") {
                    mgr.destroyEngine()
                }
                .buttonStyle(.bordered)
                .tint(.red)
                .disabled(!mgr.isEngineCreated)
            }

            HStack(spacing: 12) {
                Button("连接") {
                    let audioTrack = AoqTrackParam()
                    audioTrack.trackType = .audio
                    let videoTrack = AoqTrackParam()
                    videoTrack.trackType = .video
                    let dataTrack = AoqTrackParam()
                    dataTrack.trackType = .data
                    mgr.connect(token: token,
                                sid: sid,
                                certificate: certificate,
                                relayEndpoints: parseRelayEndpoints(json: relayEndpointsJSON),
                                workspaceIdHash: workspaceIdHash,
                                publishTracks: [audioTrack, videoTrack, dataTrack],
                                subscribeTracks: [audioTrack, videoTrack, dataTrack])
                }
                .buttonStyle(.borderedProminent)
                .disabled(!mgr.isEngineCreated || mgr.isConnected)

                Button("断开") {
                    mgr.disconnect()
                }
                .buttonStyle(.bordered)
                .tint(.red)
                .disabled(!mgr.isConnected)
            }
        }
    }

    // MARK: - DataMsg

    /* relay 接入点 JSON 多行编辑器 */
    private var relayEndpointsEditor: some View {
        VStack(alignment: .leading, spacing: 4) {
            HStack(alignment: .top) {
                Text("RelayEndpoints")
                    .frame(width: 110, alignment: .leading)
                    .foregroundStyle(.secondary)
                TextEditor(text: $relayEndpointsJSON)
                    .font(.system(.caption, design: .monospaced))
                    .frame(minHeight: 80, maxHeight: 140)
                    .overlay(
                        RoundedRectangle(cornerRadius: 4)
                            .stroke(Color.secondary.opacity(0.3))
                    )
            }
            Text("格式：[{\"endpoint\":\"ip\",\"port\":8443}]，由服务器返回或手动编辑")
                .font(.caption2)
                .foregroundStyle(.secondary)
        }
    }

    private var datamsgCard: some View {
        CardSection(title: "消息操作") {
            LabeledInput(label: "内容", text: $datamsgText, placeholder: "输入消息内容")
            Button("发送消息") {
                mgr.sendDataMsg(text: datamsgText)
            }
            .buttonStyle(.bordered)
        }
        .opacity(mgr.isEngineCreated ? 1 : 0.5)
        .disabled(!mgr.isEngineCreated)
    }

    // MARK: - Log

    private var logCard: some View {
        CardSection(title: "回调事件日志") {
            Button("清空") { mgr.clearLog() }
                .buttonStyle(.borderless)
                .frame(maxWidth: .infinity, alignment: .trailing)
        } content: {
            LogView(events: mgr.events)
        }
    }
}

#Preview {
    NavigationStack {
        LinkAPIView()
    }
}
