package com.example.livingai.pages.ratings

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.livingai.domain.model.AnimalRating
import com.example.livingai.domain.usecases.GetAnimalDetails
import com.example.livingai.domain.usecases.GetAnimalRatings
import com.example.livingai.domain.usecases.SetAnimalRatings
import com.example.livingai.pages.ratings.util.provideEmptyAnimalRating
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

class RatingViewModel(
    private val getAnimalDetails: GetAnimalDetails,
    private val getAnimalRatings: GetAnimalRatings,
    private val setAnimalRatings: SetAnimalRatings,
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val _ratingState = MutableStateFlow<AnimalRating?>(null)
    val ratingState = _ratingState.asStateFlow()

    private val _animalImages = MutableStateFlow<List<String>>(emptyList())
    val animalImages = _animalImages.asStateFlow()

    private val animalId: String = savedStateHandle.get<String>("animalId")!!

    init {
        loadAnimalDetails()
        loadAnimalRatings()
    }

    private fun loadAnimalDetails() {
        getAnimalDetails(animalId).onEach {
            _animalImages.value = it?.images ?: emptyList()
        }.launchIn(viewModelScope)
    }

    private fun loadAnimalRatings() {
        getAnimalRatings(animalId).onEach {
            _ratingState.value = it ?: provideEmptyAnimalRating(animalId)
        }.launchIn(viewModelScope)
    }

    fun onRatingChange(newRating: AnimalRating) {
        _ratingState.value = newRating
    }

    fun saveRatings() {
        viewModelScope.launch {
            _ratingState.value?.let { 
                setAnimalRatings(it)
            }
        }
    }
}
