package com.example.elva.ui.dashboard

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import javax.inject.Inject
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import com.example.elva.data.repository.HealthRepository
import com.example.elva.data.repository.DashboardSummary
import java.time.LocalDate

@HiltViewModel
class DashboardViewModel @Inject constructor(
    private val healthRepository: HealthRepository
) : ViewModel() {

    private val _dashboardSummary = MutableStateFlow<DashboardSummary?>(null)
    val dashboardSummary: StateFlow<DashboardSummary?> = _dashboardSummary

    private val _isLoading = MutableStateFlow(true)
    val isLoading: StateFlow<Boolean> = _isLoading

    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error

    init {
        loadDashboardData()
    }

    fun loadDashboardData() {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                val summary = healthRepository.getDashboardSummary()
                _dashboardSummary.value = summary
                _error.value = null
            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _isLoading.value = false
            }
        }
    }

    fun addWater(amount: Int) {
        viewModelScope.launch {
            try {
                healthRepository.addWater(LocalDate.now(), amount)
                loadDashboardData()
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun refresh() {
        loadDashboardData()
    }
}



