package com.syaroful.agrilinkvocpro.plant_disease_detection_feature.presentation.detail

import android.graphics.Bitmap
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.extention.toBase64
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.core.extention.toByteArray
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.local.entity.PlantDiagnosisEntity
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.model.PlantDiseaseDetectionResponse
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.repository.PlantDiagnosisLocalRepository
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.repository.PlantDiagnosisRepository
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class PlantDiagnosisViewModel(
    private val repository: PlantDiagnosisRepository,
    private val localRepository: PlantDiagnosisLocalRepository
) : ViewModel() {
    private val _state = MutableStateFlow<Result<PlantDiseaseDetectionResponse>?>(null)
    val state: StateFlow<Result<PlantDiseaseDetectionResponse>?> = _state

    private val _saveLoadingState = MutableStateFlow(false)
    val saveLoadingState: StateFlow<Boolean> = _saveLoadingState

    fun analyzePlant(bitmap: Bitmap, prompt: String) {
        Log.d("PlantDiagnosisViewModel", "analyzePlant() called")
        viewModelScope.launch {
            try {
                val base64 = bitmap.toBase64()
                val result = repository.detectDisease(prompt = prompt, base64Image = base64)
                _state.value = Result.success(result)
                Log.d("PlantDiagnosisViewModel", "Diagnosis result: $result")
            } catch (e: Exception) {
                _state.value = Result.failure(e)
                Log.e("PlantDiagnosisViewModel", "Error during diagnosis", e)
            }
        }
    }

    fun saveResultToLocal(response: PlantDiseaseDetectionResponse, image: Bitmap) {
        _saveLoadingState.value = true
        viewModelScope.launch {
            delay(1000L)
            val entity = PlantDiagnosisEntity(
                diagnosis = response.diagnosis ?: "Unknown",
                cause = response.cause ?: "-",
                description = response.description ?: "-",
                prevention = response.prevention?.joinToString(", ") ?: "-",
                image = image.toByteArray(),
                treatment = response.treatment?.joinToString(", ") {
                    "${it.method}: ${it.description}"
                } ?: "-",
            )
            localRepository.saveDiagnosis(entity)
            _saveLoadingState.value = false
        }
    }
}