import SwiftUI

struct LoginView: View {
    @Environment(AppEnvironment.self) private var env

    @State private var email = ""
    @State private var password = ""
    @State private var remember = true
    @State private var phase: LoadPhase = .idle
    @State private var didPrefill = false

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    TextField("Email", text: $email)
                        .textContentType(.username)
                        .keyboardType(.emailAddress)
                        .textInputAutocapitalization(.never)
                        .autocorrectionDisabled()
                    SecureField("Password", text: $password)
                        .textContentType(.password)
                    Toggle("Remember me", isOn: $remember)
                } header: {
                    Text("Sign in")
                } footer: {
                    if let host = env.configuration?.host {
                        Text("Connecting to \(host)")
                    }
                }

                Section {
                    Button {
                        Task { await signIn() }
                    } label: {
                        HStack {
                            Spacer()
                            if phase == .loading { ProgressView() } else { Text("Sign in") }
                            Spacer()
                        }
                    }
                    .disabled(email.isEmpty || password.isEmpty || phase == .loading)
                }

                if case .failed(let msg) = phase {
                    Section { Text(msg).foregroundStyle(.red).font(.footnote) }
                }
            }
            .navigationTitle("MCMS")
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    NavigationLink {
                        SettingsView(isInitialSetup: false)
                    } label: {
                        Image(systemName: "gearshape")
                    }
                }
            }
            .onAppear {
                // Prefill from the Keychain ONCE — onAppear fires again when the
                // user returns from Settings, and re-running this would wipe any
                // credentials they'd already typed.
                guard !didPrefill else { return }
                didPrefill = true
                email = env.savedEmail ?? ""
                password = env.savedPassword ?? ""
            }
        }
    }

    private func signIn() async {
        phase = .loading
        do {
            try await env.signIn(email: email, password: password, remember: remember)
            phase = .loaded
        } catch {
            phase = .failed((error as? APIError)?.localizedDescription ?? error.localizedDescription)
        }
    }
}
