package com.example.uitugasakhir.ui_otomatis

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import android.widget.Toast
import androidx.compose.ui.platform.LocalContext
import com.example.app.ui.theme.Inria_Regular
import org.eclipse.paho.client.mqttv3.*

import org.json.JSONObject
import android.util.Log
import com.example.uitugasakhir.R
import com.example.uitugasakhir.model.AmbangBatas
import com.example.uitugasakhir.api.ApiAmbangBatas

import com.example.uitugasakhir.mqtt.MqttManager

@Composable
fun AmbangBatasSection() {

    val context = LocalContext.current

    var popupMessage by remember { mutableStateOf("") }

    val mqtt = remember {
        MqttManager(context)
    }

    var showPopup by remember { mutableStateOf(false) }
    var ledState by remember { mutableStateOf(0) }
    var buzzerState by remember { mutableStateOf(0) }

    // ================= STATE =================

    var isLoadingSave by remember { mutableStateOf(false) }

    var showDialog by remember { mutableStateOf(false) }
    var currentField by remember { mutableStateOf("") }

    var ambang by remember { mutableStateOf<AmbangBatas?>(null) }
    var criticalTanah by remember { mutableStateOf("") }

    var minTanah by remember { mutableStateOf("") }
    var maxTanah by remember { mutableStateOf("") }

    var minSuhu by remember { mutableStateOf("") }
    var maxSuhu by remember { mutableStateOf("") }

    var minUdara by remember { mutableStateOf("") }
    var maxUdara by remember { mutableStateOf("") }

    var isSaved by remember { mutableStateOf(false) }

    // ================= LOAD DATA =================

    LaunchedEffect(Unit) {
        ApiAmbangBatas.getAmbangBatas(
            context = context,
            onSuccess = {
                ambang = it
                minTanah = it.min_tanah.toString()
                maxTanah = it.max_tanah.toString()
                minSuhu = it.min_suhu.toString()
                maxSuhu = it.max_suhu.toString()
                minUdara = it.min_udara.toString()
                maxUdara = it.max_udara.toString()
                criticalTanah = it.critical_tanah.toString()
                isSaved = true
            },
            onError = {
                Toast.makeText(
                    context,
                    it,
                    Toast.LENGTH_SHORT
                ).show()
            }
        )
    }

    // ================= TITLE =================

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.Start
    ) {

        Text(
            text = "Atur ambang batas",
            fontSize = 15.sp,
            fontFamily = Inria_Regular,
            fontWeight = FontWeight.Medium,
            color = Color.Gray,
        )

        Spacer(modifier = Modifier.width(15.dp))
    }

    Spacer(modifier = Modifier.height(15.dp))

    // ================= CARD =================

    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(24.dp),
        colors = CardDefaults.cardColors(
            Color(0xFFEDEDED)
        ),
        elevation = CardDefaults.cardElevation(4.dp)
    ) {

        Column {

            SettingItem(
                title = "Kelembapan tanah",
                minValue = minTanah,
                maxValue = maxTanah,
                isSaved = true,
                iconRes = R.drawable.decagon,
                onEditClick = {
                    currentField = "tanah"
                    showDialog = true
                }
            )

            HorizontalDivider(
                modifier = Modifier.padding(horizontal = 16.dp)
            )

            SettingItem(
                title = "Suhu udara",
                minValue = minSuhu,
                maxValue = maxSuhu,
                isSaved = true,
                iconRes = R.drawable.thermometer,
                onEditClick = {
                    currentField = "suhu"
                    showDialog = true
                }
            )

            HorizontalDivider(
                modifier = Modifier.padding(horizontal = 16.dp)
            )
        }
    }

    // ================= DIALOG =================

    if (showDialog) {

        AlertDialog(
            onDismissRequest = {
                showDialog = false
            },

            title = {
                Text("Atur Ambang Batas - $currentField")
            },

            text = {

                Column {

                    // MIN
                    Text("Minimal (%)")

                    TextField(
                        value = when (currentField) {
                            "tanah" -> minTanah
                            "suhu" -> minSuhu
                            else -> minUdara
                        },

                        onValueChange = { value ->

                            when (currentField) {

                                "tanah" -> minTanah = value

                                "suhu" -> minSuhu = value

                                "udara" -> minUdara = value
                            }
                        },

                        singleLine = true
                    )

                    Spacer(modifier = Modifier.height(12.dp))

                    // MAX
                    Text("Maksimal (%)")

                    TextField(
                        value = when (currentField) {
                            "tanah" -> maxTanah
                            "suhu" -> maxSuhu
                            else -> maxUdara
                        },

                        onValueChange = { value ->

                            when (currentField) {

                                "tanah" -> maxTanah = value

                                "suhu" -> maxSuhu = value

                                "udara" -> maxUdara = value
                            }
                        },

                        singleLine = true
                    )

                    if (currentField == "tanah") {

                        Spacer(modifier = Modifier.height(12.dp))

                        Text("Critical (%)")

                        TextField(
                            value = criticalTanah,
                            onValueChange = { criticalTanah = it },
                            singleLine = true
                        )
                    }
                }
            },

            confirmButton = {

                TextButton(
                    onClick = {
                        // 1. SAVE DATABASE (backup)
                        ApiAmbangBatas.saveAmbangBatas(
                            context = context,
                            minTanah = minTanah.toIntOrNull() ?: 0,
                            maxTanah = maxTanah.toIntOrNull() ?: 0,
                            minSuhu = minSuhu.toIntOrNull() ?: 0,
                            maxSuhu = maxSuhu.toIntOrNull() ?: 0,
                            minUdara = minUdara.toIntOrNull() ?: 0,
                            maxUdara = maxUdara.toIntOrNull() ?: 0,
                            criticalTanah = maxTanah.toIntOrNull() ?: 0,
                            onSuccess = {
                                Toast.makeText(context, "Saved DB", Toast.LENGTH_SHORT).show()
                            },
                            onError = {
                                Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
                            }
                        )

                        // 2. MQTT REALTIME SEND (INI YANG PENTING)
                        mqtt.publish(
                            "iot/config/update",
                            buildThresholdJson(
                                minTanah,
                                maxTanah,
                                criticalTanah,
                                minSuhu,
                                maxSuhu,
                                minUdara,
                                maxUdara
                            )
                        )

                        Toast.makeText(context, "Sent to ESP32", Toast.LENGTH_SHORT).show()

                        showDialog = false
                    }
                ) {
                    Text("Simpan")
                }
            },

            dismissButton = {

                TextButton(
                    onClick = {
                        showDialog = false
                    }
                ) {
                    Text("Batal")
                }
            }
        )
    }
}

@Composable
fun SettingItem(
    title: String,
    minValue: String,
    maxValue: String,
    isSaved: Boolean,
    iconRes: Int,
    onEditClick: () -> Unit
) {

    Column(
        modifier = Modifier.padding(top = 8.dp)
    ) {

        // TITLE

        Row(
            modifier = Modifier
                .padding(horizontal = 15.dp)
                .fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {

            Row(
                modifier = Modifier.width(170.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {

                Image(
                    painter = painterResource(id = iconRes),
                    contentDescription = null,
                    modifier = Modifier.size(18.dp),
                    colorFilter = ColorFilter.tint(Color(0xFF6B6666))
                )

                Text(
                    text = title,
                    fontSize = 15.sp,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.padding(start = 9.dp)
                )
            }
        }

        Spacer(modifier = Modifier.height(6.dp))

        // CONTENT

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 43.dp, end = 15.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {

            Column {

                Text(
                    text = "Min: $minValue%",
                    fontSize = 15.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black.copy(alpha = 0.7f)
                )

                Text(
                    text = "Max: $maxValue%",
                    fontSize = 15.sp,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black.copy(alpha = 0.7f)
                )
            }

            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {

                Text(
                    text = if (isSaved)
                        "Tersimpan"
                    else
                        "Belum diatur",

                    fontSize = 10.sp,
                    color = Color.Gray
                )

                Spacer(modifier = Modifier.width(5.dp))

                if (isSaved) {

                    Image(
                        painter = painterResource(id = R.drawable.checked),
                        contentDescription = null,
                        modifier = Modifier.size(13.dp)
                    )
                }

                Spacer(modifier = Modifier.width(5.dp))

                Box(
                    modifier = Modifier
                        .size(30.dp)
                        .clickable {
                            onEditClick()
                        },

                    contentAlignment = Alignment.Center
                ) {

                    Image(
                        painter = painterResource(id = R.drawable.edit_text),
                        contentDescription = "edit",
                        modifier = Modifier.size(18.dp)
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(8.dp))
    }
}

fun buildThresholdJson(
    minTanah: String,
    maxTanah: String,
    criticalTanah: String,
    minSuhu: String,
    maxSuhu: String,
    minUdara: String,
    maxUdara: String
): String {
    return """
    {
        "type": "threshold",
        "tanah": {
            "min": ${minTanah.toIntOrNull() ?: 0},
            "max": ${maxTanah.toIntOrNull() ?: 0},
            "critical": ${criticalTanah.toIntOrNull() ?: 0}
        },
        "suhu": {
            "min": ${minSuhu.toIntOrNull() ?: 0},
            "max": ${maxSuhu.toIntOrNull() ?: 0}
        },
        "udara": {
            "min": ${minUdara.toIntOrNull() ?: 0},
            "max": ${maxUdara.toIntOrNull() ?: 0}
        }
    }
    """.trimIndent()
}