package com.example.uitugasakhir.ui_otomatis

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
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 com.example.app.ui.theme.Inria_Regular
import com.example.app.ui.theme.Poppins_Black
import com.example.uitugasakhir.R
import com.example.uitugasakhir.api.RetrofitClient
import kotlinx.coroutines.launch

@Composable
fun JedaPenyiramanCard(
    onJedaChanged: (Int) -> Unit
) {

    var jeda by remember { mutableStateOf("") }
    var selectedUnit by remember { mutableStateOf("Detik") }
    var expanded by remember { mutableStateOf(false) }

    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    LaunchedEffect(Unit) {
        try {
            val response = RetrofitClient.api.getJeda()
            if (response.isSuccessful) {

                val body = response.body()

                if (body?.success == true) {

                    val detik = body.data?.jeda?.toIntOrNull() ?: 0

                    jeda = detik.toString()

                    onJedaChanged(detik)

                    selectedUnit = "Detik"
                }
            }
        } catch (e: Exception) {

            Log.e("JEDA", e.message.toString())
        }
    }

    Column(modifier = Modifier.fillMaxWidth()) {

        Row {
            Text(
                text = "Atur jeda penyiraman",
                fontSize = 15.sp,
                fontFamily = Inria_Regular,
                fontWeight = FontWeight.Medium,
                color = Color.Gray,
            )

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

            Image(
                painter = painterResource(id = R.drawable.clock),
                contentDescription = null,
                modifier = Modifier.size(14.dp)
                    .offset(y = 3.dp),
                colorFilter = ColorFilter.tint(Color(0xFF6B6666))
            )
        }

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

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

            Column(
                modifier = Modifier.padding(top = 5.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {

                Row(verticalAlignment = Alignment.CenterVertically) {

                    BasicTextField(
                        value = jeda,
                        onValueChange = {
                            if (it.all { c -> c.isDigit() }) {
                                jeda = it.take(3)
                            }
                        },
                        singleLine = true,
                        textStyle = LocalTextStyle.current.copy(
                            fontSize = 28.sp,
                            fontWeight = FontWeight.Bold,
                            fontFamily = Poppins_Black
                        ),
                        modifier = Modifier.width(60.dp),
                        decorationBox = {
                            if (jeda.isEmpty()) {
                                Text("00", fontSize = 28.sp)
                            }
                            it()
                        }
                    )

                    Box {
                        Text(
                            text = selectedUnit,
                            modifier = Modifier.clickable { expanded = true }
                        )

                        DropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false }
                        ) {
                            listOf("Detik", "Menit", "Jam").forEach {
                                DropdownMenuItem(
                                    text = { Text(it) },
                                    onClick = {
                                        selectedUnit = it
                                        expanded = false
                                    }
                                )
                            }
                        }
                    }
                }

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

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 10.dp)
                        .padding(horizontal = 20.dp),
                    horizontalArrangement = Arrangement.spacedBy(5.dp)
                ) {

                    // 🔴 HAPUS (set 0)
                    Button(
                        onClick = {
                            scope.launch {
                                try {
                                    val res = RetrofitClient.api.setJeda("0")
                                    Toast.makeText(context, res.body()?.message ?: "OK", Toast.LENGTH_SHORT).show()
                                    jeda = ""
                                } catch (e: Exception) {
                                    Log.e("JEDA", e.message.toString())
                                }
                            }
                        },
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(Color(0xFFD32F2F))
                    ) {
                        Text("Hapus", color = Color.White)
                    }

                    // 🟢 SIMPAN
                    Button(
                        onClick = {
                            if (jeda.isEmpty()) return@Button

                            val value = jeda.toInt()

                            val detik = when (selectedUnit) {
                                "Detik" -> value
                                "Menit" -> value * 60
                                "Jam" -> value * 3600
                                else -> value
                            }

                            onJedaChanged(detik)

                            scope.launch {
                                try {
                                    val res = RetrofitClient.api.setJeda(detik.toString())

                                    Toast.makeText(
                                        context,
                                        res.body()?.message ?: "Berhasil",
                                        Toast.LENGTH_SHORT
                                    ).show()

                                } catch (e: Exception) {
                                    Log.e("JEDA", e.message.toString())
                                }
                            }
                        },
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(Color(0xFF2F6F4E))
                    ) {
                        Text("Simpan", color = Color.White)
                    }
                }
            }
        }
    }
}