package com.devlab.app.ui.dashboard

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.devlab.app.ServerManagerApp
import com.devlab.app.data.model.DashboardStats
import com.devlab.app.data.repository.DashboardRepository
import com.devlab.app.util.PreferencesManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class DashboardUiState(
    val isLoading: Boolean = true,
    val stats: DashboardStats? = null,
    val error: String? = null,
    val username: String = ""
)

class DashboardViewModel : ViewModel() {

    private val repository = DashboardRepository()
    private val prefs = PreferencesManager(ServerManagerApp.instance)

    private val _uiState = MutableStateFlow(DashboardUiState())
    val uiState: StateFlow<DashboardUiState> = _uiState.asStateFlow()

    init {
        viewModelScope.launch {
            val savedUsername = prefs.getUsername()
            _uiState.value = _uiState.value.copy(username = savedUsername)
        }
        loadStats()
    }

    fun loadStats() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, error = null)
            try {
                val response = repository.getStatus()
                if (response.success) {
                    _uiState.value = DashboardUiState(
                        isLoading = false,
                        stats = response.data,
                        username = _uiState.value.username
                    )
                } else {
                    _uiState.value = DashboardUiState(
                        isLoading = false,
                        error = response.error ?: "Failed to load stats",
                        username = _uiState.value.username
                    )
                }
            } catch (e: Exception) {
                _uiState.value = DashboardUiState(
                    isLoading = false,
                    error = e.message ?: "Network error",
                    username = _uiState.value.username
                )
            }
        }
    }
}
