package com.syaroful.agrilinkvocpro.growth_recipe_feature.presentation.recomendation

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.syaroful.agrilinkvocpro.core.utils.ResultState
import com.syaroful.agrilinkvocpro.core.utils.extention.mapToUserFriendlyError
import com.syaroful.agrilinkvocpro.growth_recipe_feature.data.model.ClusteringResponse
import com.syaroful.agrilinkvocpro.growth_recipe_feature.data.repository.ClusteringRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

private const val TAG = "ClusterViewModel"

class ClusterViewModel(private val repository: ClusteringRepository) : ViewModel() {

    private val _state =
        MutableStateFlow<ResultState<ClusteringResponse>>(ResultState.Idle)
    val state: StateFlow<ResultState<ClusteringResponse>> = _state.asStateFlow()

    fun getRecommendation(
    ) {
        _state.value = ResultState.Loading
        viewModelScope.launch {
            try {
                val response = repository.getRecommendation()
                if (response.isNotEmpty()) {
                    val data = response.last()
                    _state.value = ResultState.Success(data)
                } else {
                    _state.value = ResultState.Error("Data tidak ditemukan")
                }
            } catch (e: Exception) {
                val errorMessage = mapToUserFriendlyError(e)
                _state.value = ResultState.Error(errorMessage)
                Log.d(TAG, "Failed to fetch data: ${e.message}")
            }
        }
    }
}