import SwiftUI

struct AddServerView: View {
    @Environment(AppState.self) private var appState
    @Environment(\.dismiss) private var dismiss

    let editing: SavedServer?

    @State private var host = ""
    @State private var port = "7878"
    @State private var authMode = SavedServer.AuthMode.guest
    @State private var nickname = ""
    @State private var username = ""
    @State private var password = ""
    @State private var savePassword = false

    var body: some View {
        NavigationStack {
            Form {
                Section("Server") {
                    TextField("Hostname or IP", text: $host)
                        .textContentType(.URL)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)
                        .accessibilityLabel("Server hostname or IP address")
                    TextField("Port", text: $port)
                        .keyboardType(.numberPad)
                        .accessibilityLabel("Port number")
                }

                Section("Authentication") {
                    Picker("Mode", selection: $authMode) {
                        Text("Guest").tag(SavedServer.AuthMode.guest)
                        Text("Account").tag(SavedServer.AuthMode.password)
                    }
                    .pickerStyle(.segmented)
                    .accessibilityLabel("Authentication mode")

                    if authMode == .guest {
                        TextField("Nickname (optional)", text: $nickname)
                            .autocorrectionDisabled()
                            .textInputAutocapitalization(.never)
                            .accessibilityLabel("Guest nickname, optional display name")
                    }

                    if authMode == .password {
                        TextField("Username", text: $username)
                            .textContentType(.username)
                            .autocorrectionDisabled()
                            .textInputAutocapitalization(.never)
                            .accessibilityLabel("Username")
                        SecureField("Password (optional)", text: $password)
                            .textContentType(.password)
                            .accessibilityLabel("Password, optional, leave blank to enter at connect time")
                        Toggle("Save password in Keychain", isOn: $savePassword)
                    }
                }
            }
            .navigationTitle(editing == nil ? "Add Server" : "Edit Server")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") { save() }
                        .disabled(host.trimmingCharacters(in: .whitespaces).isEmpty
                                  || UInt16(port) == nil)
                }
            }
        }
        .onAppear {
            if let s = editing {
                host = s.host
                port = "\(s.port)"
                authMode = s.authMode
                username = s.savedUsername
                nickname = s.nickname ?? ""
            }
        }
    }

    private func save() {
        let trimmedHost = host.trimmingCharacters(in: .whitespaces)
        guard !trimmedHost.isEmpty, let portNum = UInt16(port) else { return }

        let pw = (savePassword && authMode == .password && !password.isEmpty) ? password : nil
        let trimmedNick = nickname.trimmingCharacters(in: .whitespaces)
        let nick: String? = (authMode == .guest && !trimmedNick.isEmpty) ? trimmedNick : nil

        if var s = editing {
            s.host = trimmedHost
            s.port = portNum
            s.authMode = authMode
            s.savedUsername = authMode == .password ? username : ""
            s.nickname = nick
            appState.updateServer(s, password: pw)
        } else {
            let s = SavedServer(host: trimmedHost, port: portNum,
                                authMode: authMode,
                                savedUsername: authMode == .password ? username : "",
                                nickname: nick)
            appState.addServer(s, password: pw)
        }
        dismiss()
    }
}
