package org.zaine.management.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.zaine.management.data.BackendRepository
import org.zaine.management.data.NetworkResult
import org.zaine.management.data.SessionStore
import javax.inject.Inject

data class LoginUiState(
    val baseUrl: String = "",
    val username: String = "",
    val password: String = "",
    val loading: Boolean = false,
    val error: String? = null,
    val loggedIn: Boolean = false
)

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val repository: BackendRepository,
    sessionStore: SessionStore
) : ViewModel() {
    private val _state = MutableStateFlow(LoginUiState(baseUrl = sessionStore.baseUrl))
    val state: StateFlow<LoginUiState> = _state.asStateFlow()

    fun setBaseUrl(value: String) = update { copy(baseUrl = value) }
    fun setUsername(value: String) = update { copy(username = value) }
    fun setPassword(value: String) = update { copy(password = value) }

    fun login() {
        val current = _state.value
        val baseUrl = current.baseUrl.trim()
        val username = current.username.trim()
        val password = current.password
        if (baseUrl.isBlank() || username.isBlank() || password.isBlank()) {
            update { copy(error = "Base URL, username, and password are required") }
            return
        }
        viewModelScope.launch {
            update { copy(loading = true, error = null) }
            when (val result = repository.login(baseUrl, username, password)) {
                is NetworkResult.Success -> update { copy(loading = false, loggedIn = true) }
                is NetworkResult.Error -> update { copy(loading = false, error = result.message) }
                NetworkResult.Loading -> Unit
            }
        }
    }

    private fun update(block: LoginUiState.() -> LoginUiState) {
        _state.value = _state.value.block()
    }
}
