package com.example.elva.ui.health

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.elva.data.models.health.*
import com.example.elva.data.repository.HealthRepository
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 java.time.LocalDate
import javax.inject.Inject

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

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

    private val _selectedDate = MutableStateFlow(LocalDate.now())
    val selectedDate: StateFlow<LocalDate> = _selectedDate.asStateFlow()

    init {
        loadHealthData()
    }

    fun loadHealthData() {
        viewModelScope.launch {
            try {
                val today = LocalDate.now()

                // Load all data
                val cycleStats = healthRepository.calculateCycleStats()
                val waterIntake = healthRepository.getWaterIntakeForDate(today)
                val waterGoal = healthRepository.getWaterGoal()
                val calorieEntries = healthRepository.getCalorieEntriesForDate(today)
                val calorieGoal = healthRepository.getCalorieGoal()
                val latestWeight = healthRepository.getLatestWeight()
                val sleepEntry = healthRepository.getSleepEntryForDate(today)
                val sleepGoal = healthRepository.getSleepGoal()
                val avgSleep = healthRepository.getAverageSleepHours()

                _uiState.value = HealthUiState.Success(
                    cycleStats = cycleStats,
                    waterIntake = waterIntake?.amountMl ?: 0,
                    waterGoal = waterGoal,
                    caloriesConsumed = calorieEntries.sumOf { it.calories },
                    calorieGoal = calorieGoal.dailyGoal,
                    currentWeight = latestWeight?.weightKg,
                    todaySleep = sleepEntry?.durationHours,
                    sleepGoal = sleepGoal,
                    averageSleep = avgSleep
                )
            } catch (e: Exception) {
                _uiState.value = HealthUiState.Error(e.message ?: "Unknown error")
            }
        }
    }

    fun setSelectedDate(date: LocalDate) {
        _selectedDate.value = date
    }

    // Water tracking
    fun addWater(amountMl: Int) {
        viewModelScope.launch {
            healthRepository.addWater(LocalDate.now(), amountMl)
            loadHealthData()
        }
    }

    fun setWaterGoal(goalMl: Int) {
        viewModelScope.launch {
            healthRepository.setWaterGoal(goalMl)
            loadHealthData()
        }
    }

    // Calorie tracking
    fun addCalorieEntry(calories: Int, mealType: MealType, description: String = "") {
        viewModelScope.launch {
            val entry = CalorieEntry(
                date = LocalDate.now(),
                calories = calories,
                mealType = mealType,
                description = description
            )
            healthRepository.addCalorieEntry(entry)
            loadHealthData()
        }
    }

    fun setCalorieGoal(goal: CalorieGoal) {
        viewModelScope.launch {
            healthRepository.setCalorieGoal(goal)
            loadHealthData()
        }
    }

    // Weight tracking
    fun addWeightEntry(weightKg: Float, notes: String = "") {
        viewModelScope.launch {
            val entry = WeightEntry(
                date = LocalDate.now(),
                weightKg = weightKg,
                notes = notes
            )
            healthRepository.addWeightEntry(entry)
            loadHealthData()
        }
    }

    // Sleep tracking
    fun addSleepEntry(entry: SleepEntry) {
        viewModelScope.launch {
            healthRepository.addSleepEntry(entry)
            loadHealthData()
        }
    }

    fun setSleepGoal(hours: Float) {
        viewModelScope.launch {
            healthRepository.setSleepGoal(hours)
            loadHealthData()
        }
    }

    // Period tracking
    fun addPeriod(period: Period) {
        viewModelScope.launch {
            healthRepository.addPeriod(period)
            loadHealthData()
        }
    }

    fun updatePeriod(period: Period) {
        viewModelScope.launch {
            healthRepository.updatePeriod(period)
            loadHealthData()
        }
    }

    fun deletePeriod(periodId: Long) {
        viewModelScope.launch {
            healthRepository.deletePeriod(periodId)
            loadHealthData()
        }
    }
}

sealed class HealthUiState {
    object Loading : HealthUiState()
    data class Success(
        val cycleStats: CycleStats,
        val waterIntake: Int,
        val waterGoal: Int,
        val caloriesConsumed: Int,
        val calorieGoal: Int,
        val currentWeight: Float?,
        val todaySleep: Float?,
        val sleepGoal: Float,
        val averageSleep: Float
    ) : HealthUiState()
    data class Error(val message: String) : HealthUiState()
}

