import SwiftUI

/// 连接鉴权弹窗：免密 / 动态验证码 / 固定密码（对应 Android 的鉴权对话框）。
struct AuthSheetView: View {
    @Environment(\.dismiss) private var dismiss

    let onConfirm: (AuthType, String) -> Void

    @State private var authType: AuthType = .none
    @State private var authValue: String = ""

    var body: some View {
        NavigationView {
            Form {
                Section("鉴权方式") {
                    Picker("鉴权方式", selection: $authType) {
                        ForEach(AuthType.allCases) { type in
                            Text(type.title).tag(type)
                        }
                    }
                    .pickerStyle(.segmented)
                }

                if authType != .none {
                    Section(authType == .code ? "验证码" : "密码") {
                        if authType == .code {
                            TextField("请输入被控端显示的 6 位验证码", text: $authValue)
                                .keyboardType(.numberPad)
                        } else {
                            SecureField("请输入被控端设置的连接密码", text: $authValue)
                        }
                    }
                }

                Section {
                    Button {
                        onConfirm(authType, authValue)
                    } label: {
                        HStack {
                            Spacer()
                            Text("开始连接")
                                .fontWeight(.semibold)
                            Spacer()
                        }
                    }
                    .disabled(authType != .none && authValue.isEmpty)
                } footer: {
                    Text(footerTips)
                }
            }
            .navigationTitle("连接鉴权")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") { dismiss() }
                }
            }
        }
        .navigationViewStyle(.stack)
    }

    private var footerTips: String {
        switch authType {
        case .none:
            return "免密连接：需要被控端手动确认或开启免验证。"
        case .code:
            return "动态验证码：输入被控端界面上显示的验证码，验证通过后自动接受连接。"
        case .password:
            return "固定密码：输入被控端预设的连接密码，验证通过后自动接受连接。"
        }
    }
}
