import SwiftUI

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

    @State private var username = ""
    @State private var password = ""

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    if let server = appState.connectingServer {
                        Text("Connecting to \(server.displayString)")
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                    if appState.connectingServer?.authMode == .password {
                        TextField("Username", text: $username)
                            .textContentType(.username)
                            .autocorrectionDisabled()
                            .textInputAutocapitalization(.never)
                            .accessibilityLabel("Username")
                    }
                    SecureField("Password", text: $password)
                        .textContentType(.password)
                        .accessibilityLabel("Password")
                }

                if !appState.connectStatus.isEmpty && appState.connectStatus.lowercased().contains("failed") {
                    Section {
                        Text(appState.connectStatus)
                            .foregroundStyle(.red)
                            .accessibilityLabel("Error: \(appState.connectStatus)")
                    }
                }
            }
            .navigationTitle("Sign In")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") {
                        dismiss()
                        appState.cancelConnect()
                    }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Connect") {
                        dismiss()
                        let uname = appState.connectingServer?.savedUsername.isEmpty == false
                            ? appState.connectingServer!.savedUsername
                            : username
                        appState.authenticateUser(username: uname, password: password)
                    }
                    .disabled(password.isEmpty)
                }
            }
        }
        .onAppear {
            username = appState.connectingServer?.savedUsername ?? ""
        }
        .interactiveDismissDisabled()
    }
}
