package com.example.elva.ui.dashboard

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.launch
import java.time.LocalDate
import javax.inject.Inject

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

    private val _state = MutableStateFlow(HealthState())
    val state: StateFlow<HealthState> = _state

    init {
        loadTodayData()
    }

    fun loadTodayData() {
        val today = LocalDate.now()
        viewModelScope.launch {
            try {
                val waterIntakeData = healthRepository.getWaterIntakeForDate(today)
                val waterGoal = healthRepository.getWaterGoal()
                val waterIntake = WaterIntakeOld(
                    date = today,
                    amount = waterIntakeData?.amountMl ?: 0,
                    goal = waterGoal
                )

                val totalCalories = healthRepository.getTotalCaloriesForDate(today)
                val calorieGoal = healthRepository.getCalorieGoal()
                val calories = CalorieIntake(
                    date = today,
                    calories = totalCalories,
                    goal = calorieGoal.dailyGoal
                )

                val sleep = healthRepository.getSleepEntry(today)
                val weightEntries = healthRepository.getWeightEntries()
                val cycleInfo = healthRepository.getCycleInfo()

                _state.value = _state.value.copy(
                    waterIntake = waterIntake,
                    calorieIntake = calories,
                    sleepEntry = sleep,
                    latestWeight = weightEntries.maxByOrNull { it.date }?.weightKg,
                    cycleInfo = cycleInfo,
                    isLoading = false
                )
            } catch (e: Exception) {
                _state.value = _state.value.copy(
                    error = e.message,
                    isLoading = false
                )
            }
        }
    }

    fun addWater(amount: Int) {
        viewModelScope.launch {
            val today = LocalDate.now()
            healthRepository.addWater(today, amount)
            val updated = healthRepository.getWaterIntakeForDate(today)
            val waterGoal = healthRepository.getWaterGoal()
            _state.value = _state.value.copy(
                waterIntake = WaterIntakeOld(
                    date = today,
                    amount = updated?.amountMl ?: amount,
                    goal = waterGoal
                )
            )
        }
    }

    fun addCalories(calories: Int) {
        viewModelScope.launch {
            val entry = CalorieEntry(
                date = LocalDate.now(),
                calories = calories,
                mealType = MealType.SNACK,
                description = "Перекус",
                timestamp = java.time.LocalDateTime.now()
            )
            healthRepository.addCalorieEntry(entry)
            val total = healthRepository.getTotalCaloriesForDate(LocalDate.now())
            val current = _state.value.calorieIntake
            _state.value = _state.value.copy(
                calorieIntake = current.copy(calories = total)
            )
        }
    }

    fun saveSleep(hours: Float, quality: SleepQuality, note: String? = null) {
        viewModelScope.launch {
            val now = java.time.LocalDateTime.now()
            val entry = SleepEntry(
                date = LocalDate.now(),
                sleepStart = now.minusHours(hours.toLong()),
                sleepEnd = now,
                quality = quality,
                notes = note ?: ""
            )
            healthRepository.addSleepEntry(entry)
            _state.value = _state.value.copy(sleepEntry = entry)
        }
    }

    fun saveWeight(weightKg: Float, note: String? = null) {
        viewModelScope.launch {
            val entry = WeightEntry(
                date = LocalDate.now(),
                weightKg = weightKg,
                notes = note ?: ""
            )
            healthRepository.addWeightEntry(entry)
            _state.value = _state.value.copy(latestWeight = weightKg)
        }
    }

    fun getDaysUntilNextPeriod(): Int? {
        val nextPeriod = _state.value.cycleInfo.nextPeriodPrediction ?: return null
        val today = LocalDate.now()
        return if (nextPeriod.isAfter(today)) {
            java.time.temporal.ChronoUnit.DAYS.between(today, nextPeriod).toInt()
        } else null
    }
}

data class HealthState(
    val waterIntake: WaterIntakeOld = WaterIntakeOld(date = LocalDate.now(), amount = 0),
    val calorieIntake: CalorieIntake = CalorieIntake(date = LocalDate.now(), calories = 0),
    val sleepEntry: SleepEntry? = null,
    val latestWeight: Float? = null,
    val cycleInfo: CycleInfo = CycleInfo(
        lastPeriodStart = null,
        nextPeriodPrediction = null,
        ovulationPrediction = null
    ),
    val isLoading: Boolean = true,
    val error: String? = null
)

