import SwiftUI

struct LoginView: View {
    @Environment(ConnectionManager.self) private var manager

    @AppStorage("login_email") private var email = ""
    @State private var password = ""
    @AppStorage("save_password") private var savePassword = false
    @AppStorage("use_custom_server") private var useCustomServer = false
    @AppStorage("custom_host") private var customHost = ""
    @AppStorage("custom_port") private var customPort = "4200"
    @State private var isCreatingAccount = false

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    Image(.logo)
                        .resizable()
                        .scaledToFit()
                        .frame(maxHeight: 120)
                        .clipShape(.rect(cornerRadius: 24))
                        .frame(maxWidth: .infinity)
                        .accessibilityHidden(true)
                }

                Section("Credentials") {
                    TextField("Email", text: $email)
                        .textContentType(.emailAddress)
                        .keyboardType(.emailAddress)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)

                    SecureField("Password", text: $password)
                        .textContentType(.password)

                    Toggle("Save Password", isOn: $savePassword)
                }

                Section("Server") {
                    Picker("Server", selection: $useCustomServer) {
                        Text("Default").tag(false)
                        Text("Custom").tag(true)
                    }
                    .pickerStyle(.segmented)

                    if useCustomServer {
                        TextField("Host", text: $customHost)
                            .autocorrectionDisabled()
                            .textInputAutocapitalization(.never)
                        TextField("Port", text: $customPort)
                            .keyboardType(.numberPad)
                    }
                }

                Section {
                    Toggle("Create new account", isOn: $isCreatingAccount)
                }

                Section {
                    Button {
                        connect()
                    } label: {
                        Text(isCreatingAccount ? "Create Account & Connect" : "Connect")
                            .frame(maxWidth: .infinity)
                    }
                    .disabled(email.isEmpty || password.isEmpty || (useCustomServer && customHost.isEmpty))
                }
            }
            .navigationTitle("Welcome to Kirandur Chat")
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    NavigationLink {
                        SettingsView()
                    } label: {
                        Label("Settings", systemImage: "gearshape")
                    }
                }
            }
            .alert("Error", isPresented: .init(
                get: { manager.errorMessage != nil },
                set: { if !$0 { manager.errorMessage = nil } }
            )) {
            } message: {
                Text(manager.errorMessage ?? "")
            }
            .onAppear {
                if savePassword {
                    password = KeychainHelper.load(key: "password") ?? ""
                }
            }
            .onChange(of: savePassword) {
                if !savePassword {
                    KeychainHelper.delete(key: "password")
                }
            }
        }
    }

    private func connect() {
        if savePassword {
            KeychainHelper.save(key: "password", value: password)
        }
        let host = useCustomServer ? customHost : ServerConfig.default.host
        let port = UInt16(useCustomServer ? customPort : "\(ServerConfig.default.port)") ?? ServerConfig.default.port
        manager.connect(
            host: host, port: port,
            email: email, password: password,
            createAccount: isCreatingAccount
        )
    }
}
