import Foundation
import SwiftUI

@Observable
final class AuthViewModel {
    var email = ""
    var password = ""
    var confirmPassword = ""
    var username = ""
    var confirmationCode = ""

    var isLoading = false
    var errorMessage: String?
    var showConfirmation = false
    var registrationMessage: String?

    var serverHost = Constants.defaultHost
    var serverPort = String(Constants.defaultPort)
    var useTLS = false

    enum AuthMode {
        case login, register, pairing
    }
    var mode: AuthMode = .login

    func login(appState: AppState) async {
        guard !email.isEmpty, !password.isEmpty else {
            errorMessage = "Email and password are required"
            return
        }

        isLoading = true
        errorMessage = nil

        do {
            let port = UInt16(serverPort) ?? Constants.defaultPort
            try await appState.chatClient.connect(host: serverHost, port: port, useTLS: useTLS)
        } catch {
            isLoading = false
            errorMessage = "Connection failed: \(error.localizedDescription)"
            return
        }

        let (success, message) = await appState.chatClient.login(email: email, password: password)
        isLoading = false

        if success {
            appState.email = email
            appState.isLoggedIn = true
            appState.connectionStatus = .connected
            if let userId = await appState.chatClient.userId {
                appState.currentUser = User(id: userId, username: await appState.chatClient.username, email: email)
            }
        } else {
            errorMessage = message
        }
    }

    func register(appState: AppState) async {
        guard !email.isEmpty, !password.isEmpty, !username.isEmpty else {
            errorMessage = "All fields are required"
            return
        }
        guard password == confirmPassword else {
            errorMessage = "Passwords don't match"
            return
        }

        isLoading = true
        errorMessage = nil

        do {
            let port = UInt16(serverPort) ?? Constants.defaultPort
            try await appState.chatClient.connect(host: serverHost, port: port, useTLS: useTLS)
        } catch {
            isLoading = false
            errorMessage = "Connection failed: \(error.localizedDescription)"
            return
        }

        let (success, message) = await appState.chatClient.register(username: username, password: password, email: email)
        isLoading = false

        if success {
            registrationMessage = message
            showConfirmation = true
        } else {
            errorMessage = message
        }
    }

    func confirmRegistration(appState: AppState) async {
        guard !confirmationCode.isEmpty else {
            errorMessage = "Enter the confirmation code"
            return
        }

        isLoading = true
        errorMessage = nil

        let (success, message) = await appState.chatClient.confirmRegistration(
            email: email, username: username, code: confirmationCode
        )
        isLoading = false

        if success {
            registrationMessage = message
            // Auto-login after registration
            await login(appState: appState)
        } else {
            errorMessage = message
        }
    }
}
