package viewmodel

import android.content.Context
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.uitugasakhir.api.RetrofitClient
import com.example.uitugasakhir.model.Sensor
import com.example.uitugasakhir.model.AmbangBatas
import com.example.uitugasakhir.utils.showNotification
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


import com.example.uitugasakhir.api.ApiAmbangBatas.getAmbangBatas

class NotificationViewModel : ViewModel() {

    // =========================
    // DATA
    // =========================
    var sensor by mutableStateOf<Sensor?>(null)
        private set

    var ambang by mutableStateOf<AmbangBatas?>(null)
        private set

    // =========================
    // UI STATE
    // =========================
    var warningMessage by mutableStateOf("Aman")
        private set

    var isWarningActive by mutableStateOf(false)
        private set

    private var lastPopupTime = 0L

    // =========================
    // LOAD DATA LOOP
    // =========================
    fun loadData(context: Context) {
        viewModelScope.launch {

            var notifTanah = false
            var notifSuhu = false
            var notifUdara = false

            while (true) {
                try {

                    val sensorResponse = RetrofitClient.api.getSensor()
                    val ambangResponse = RetrofitClient.api.getAmbangBatas()

                    val sensorData = Sensor(
                        kelembaban_udara = sensorResponse.kelembaban_udara.toFloat(),
                        suhu_udara = sensorResponse.suhu_udara.toFloat(),
                        kelembaban_tanah = sensorResponse.kelembaban_tanah.toFloat(),
                        intensitas_hujan = sensorResponse.intensitas_hujan.toFloat()
                    )

                    val ambangData = AmbangBatas(
                        min_tanah = ambangResponse.min_tanah,
                        max_tanah = ambangResponse.max_tanah,
                        critical_tanah = ambangResponse.critical_tanah,
                        min_suhu = ambangResponse.min_suhu,
                        max_suhu = ambangResponse.max_suhu,
                        min_udara = ambangResponse.min_udara,
                        max_udara = ambangResponse.max_udara
                    )

                    sensor = sensorData
                    ambang = ambangData

                    val warnings = mutableListOf<String>()

                    // =========================
                    // TANAH
                    // =========================
                    if (sensorData.kelembaban_tanah < ambangData.min_tanah) {
                        warnings.add("🌱 Tanah terlalu kering")

                        if (!notifTanah) {
                            showNotification(
                                context,
                                "Tanah Kering",
                                "Kelembapan tanah di bawah batas minimum"
                            )
                            notifTanah = true
                        }

                    } else if (sensorData.kelembaban_tanah > ambangData.max_tanah) {
                        warnings.add("💧 Tanah terlalu basah")

                        if (!notifTanah) {
                            showNotification(
                                context,
                                "Tanah Basah",
                                "Kelembapan tanah melebihi batas maksimum"
                            )
                            notifTanah = true
                        }

                    } else {
                        notifTanah = false
                    }

                    // =========================
                    // SUHU
                    // =========================
                    if (sensorData.suhu_udara < ambangData.min_suhu) {
                        warnings.add("❄️ Suhu terlalu dingin")

                        if (!notifSuhu) {
                            showNotification(
                                context,
                                "Suhu Rendah",
                                "Suhu udara di bawah batas minimum"
                            )
                            notifSuhu = true
                        }

                    } else if (sensorData.suhu_udara > ambangData.max_suhu) {
                        warnings.add("🔥 Suhu terlalu tinggi")

                        if (!notifSuhu) {
                            showNotification(
                                context,
                                "Suhu Tinggi",
                                "Suhu udara melebihi batas maksimum"
                            )
                            notifSuhu = true
                        }

                    } else {
                        notifSuhu = false
                    }

                    // =========================
                    // UDARA
                    // =========================
                    if (sensorData.kelembaban_udara < ambangData.min_udara) {
                        warnings.add("🌬 Udara terlalu kering")

                        if (!notifUdara) {
                            showNotification(
                                context,
                                "Udara Kering",
                                "Kelembapan udara di bawah batas minimum"
                            )
                            notifUdara = true
                        }

                    } else if (sensorData.kelembaban_udara > ambangData.max_udara) {
                        warnings.add("🌫 Udara terlalu lembab")

                        if (!notifUdara) {
                            showNotification(
                                context,
                                "Udara Lembab",
                                "Kelembapan udara melebihi batas maksimum"
                            )
                            notifUdara = true
                        }

                    } else {
                        notifUdara = false
                    }

                    // =========================
                    // UPDATE POPUP
                    // =========================
                    val now = System.currentTimeMillis()

                    if (warnings.isEmpty()) {
                        warningMessage = "Aman"
                        isWarningActive = false
                    } else {
                        warningMessage = warnings.joinToString("\n")

                        if (now - lastPopupTime > 5000) {
                            isWarningActive = true
                            lastPopupTime = now
                        }
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                }

                delay(5000)
            }
        }
    }

    fun clearWarning() {
        isWarningActive = false
    }

    fun updateFromSocket(message: String) {
        warningMessage = message
        isWarningActive = true
    }
}