package de.krisenvorrat.app.ui.messaging

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.krisenvorrat.app.domain.repository.MessageRepository
import de.krisenvorrat.shared.model.UserListItemDto
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

internal data class UserListUiState(
    val users: List<UserListItemDto> = emptyList(),
    val isLoading: Boolean = false,
    val errorMessage: String? = null
)

@HiltViewModel
internal class UserListViewModel @Inject constructor(
    private val messageRepository: MessageRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(UserListUiState(isLoading = true))
    val uiState: StateFlow<UserListUiState> = _uiState

    init {
        loadUsers()
    }

    private fun loadUsers() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null)
            val result = messageRepository.fetchUsers()
            _uiState.value = if (result.isSuccess) {
                UserListUiState(users = result.getOrDefault(emptyList()), isLoading = false)
            } else {
                UserListUiState(
                    isLoading = false,
                    errorMessage = result.exceptionOrNull()?.message ?: "Fehler beim Laden"
                )
            }
        }
    }

    fun retry() = loadUsers()
}
