package com.syaroful.agrilinkvocpro.presentation.screen.home

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.data.UserPreferences
import com.syaroful.agrilinkvocpro.data.model.SensorDataResponse
import com.syaroful.agrilinkvocpro.data.repository.SensorDataRepository
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch


private const val TAG = "HomeViewModel"

class HomeViewModel(
    private val sensorDataRepository: SensorDataRepository,
    private val userPreferences: UserPreferences
) : ViewModel() {
    private val _homeState = MutableStateFlow<ResultState<SensorDataResponse>>(ResultState.Idle)
    val homeState: StateFlow<ResultState<SensorDataResponse>> = _homeState

//    var currentDataSensor: SensorDataResponse? = null
//        private set

    init {
        getGreenHouseData()
    }
    fun printUserToken(){
        viewModelScope.launch {
            val token = userPreferences.tokenFlow.first()
            Log.d(TAG, "Token: $token")
        }
    }

    fun getGreenHouseData(){
        _homeState.value = ResultState.Loading
        viewModelScope.launch {
            val token = userPreferences.tokenFlow.first()
            val authHeader = "Bearer $token"
            try {
                delay(1000L)
                val response = sensorDataRepository.getLatestSensorData(authHeader)
                if (response.isSuccessful) {
                    val responseBody = response.body()
                    _homeState.value = ResultState.Success(responseBody)
//                    currentDataSensor = responseBody
                    Log.d(TAG, "Success to fetch data: ${response.body()} \nCurl response: ${response.raw()}")
                } else {
                    val errorBody = response.errorBody()?.string()
                    Log.d(TAG, "Failed to fetch data. Code: ${response.code()}, Error Body: $errorBody \nCurl response: ${response.raw()}")
                    val errorMessage = errorBody?.let {
                        org.json.JSONObject(it)
                            .optString("message", "Failed to fetch data: ${response.code()}")
                    } ?: "Failed to fetch data: ${response.code()}"
                    _homeState.value = ResultState.Error(errorMessage)
                }
            } catch (e: Exception){
                val errorMessage = mapToUserFriendlyError(e)
                _homeState.value = ResultState.Error(errorMessage)
                Log.d(TAG, "Failed to fetch data: ${e.message}")
            }
        }
    }
}