package com.syaroful.agrilinkvocpro.growth_recipe_feature.presentation.recipe

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.core.utils.extention.toFormattedString
import com.syaroful.agrilinkvocpro.data.UserPreferences
import com.syaroful.agrilinkvocpro.growth_recipe_feature.data.model.NpkGraphicDayResponse
import com.syaroful.agrilinkvocpro.growth_recipe_feature.data.repository.GraphicDataRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.util.Date


private const val TAG = "GrowthRecipeViewModel"

class GrowthRecipeViewModel(
    private val userPreferences: UserPreferences,
    private val growthRecipeRepository: GraphicDataRepository
) : ViewModel() {

    private val _getGraphicState =
        MutableStateFlow<ResultState<NpkGraphicDayResponse>>(ResultState.Idle)
    val getGraphicState: StateFlow<ResultState<NpkGraphicDayResponse>> =
        _getGraphicState.asStateFlow()

    private val today = Date()
    private val tenDaysAgo = Date(today.time - 9 * 24 * 60 * 60 * 1000)

    fun getGraphicData(
        sensor: String
    ) {
        _getGraphicState.value = ResultState.Loading
        viewModelScope.launch {
            val token = userPreferences.tokenFlow.first()
            val authHeader = "Bearer $token"
            val dateNow = today.toFormattedString()
            val dateTenDaysAgo = tenDaysAgo.toFormattedString()

            try {
                val response = growthRecipeRepository.getNpkDataSensor(
                    authHeader = authHeader,
                    startDate = dateTenDaysAgo,
                    endDate = dateNow,
                    timeRange = "DAILY",
                    sensor = sensor,
                )
                if (response.isSuccessful) {
                    response.body()?.let { body ->
                        _getGraphicState.value = ResultState.Success(body)
                    } ?: run {
                        _getGraphicState.value = ResultState.Error("Data tidak ditemukan")
                    }
                }
            } catch (e: Exception) {
                val errorMessage = mapToUserFriendlyError(e)
                _getGraphicState.value = ResultState.Error(errorMessage)
                Log.d(TAG, "Failed to fetch data: ${e.message}")
            }
        }
    }
}