package com.example.uitugasakhir.ui_otomatis

import android.app.TimePickerDialog
import android.content.Context
import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
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.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.app.ui.theme.Inria_Regular

import com.example.uitugasakhir.R
import com.example.uitugasakhir.model.JadwalItem

@Composable
fun JadwalSection(
    jadwalList: List<JadwalItem>,
    loadJadwal: () -> Unit,
    context: Context,
    onDeleteClick: (String) -> Unit
) {

    fun getWaktuStatus(hour: Int, minute: Int): String {
        return when {
            hour in 5..10 -> "Pagi"
            hour in 11..14 -> "Siang"
            hour in 15..18 && !(hour == 18 && minute >= 30) -> "Petang"
            hour == 18 && minute >= 30 -> "Senja"
            hour in 19..23 -> "Malam"
            else -> "Dini Hari"
        }
    }

    Column {

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

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

        Card(
            modifier = Modifier
                .fillMaxWidth()
                .heightIn(min = 150.dp, max = 350.dp),
            shape = RoundedCornerShape(20.dp),
            colors = CardDefaults.cardColors(Color(0xFFEDEDED))
        ) {

            LazyColumn {
                itemsIndexed(jadwalList) { index, item ->

                    Column{

                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {

                            Row(verticalAlignment = Alignment.CenterVertically) {

                                // 🗑️ DELETE
                                IconButton(
                                    onClick = {
                                        Log.d("DELETE_CLICK", "ID: ${item.id}")
                                        onDeleteClick(item.id)
                                    }
                                ) {
                                    Icon(
                                        painter = painterResource(id = R.drawable.trash),
                                        contentDescription = "Hapus",
                                        modifier = Modifier.size(18.dp)
                                    )
                                }

                                Text("Jadwal ${index + 1}",
                                    fontSize = 15.sp,
                                    fontWeight = FontWeight.Normal)
                            }

                            // ✏️ EDIT
                            IconButton(
                                onClick = {
                                    TimePickerDialog(
                                        context,
                                        { _, h, m ->

                                            val status = getWaktuStatus(h, m)
                                            val waktu = String.format("%02d:%02d", h, m)

                                            Log.d("EDIT_KIRIM", "ID: ${item.id}")
                                            Log.d("EDIT_KIRIM", "Waktu: $waktu")
                                            Log.d("EDIT_KIRIM", "Status: $status")

                                            val request = object : StringRequest(
                                                Request.Method.POST,
                                                "http://kopikaosmartsystem.my.id/edit_jadwal.php",

                                                { response ->
                                                    Log.d("EDIT_SUCCESS", "Response: $response")
                                                    loadJadwal()
                                                },

                                                { error ->
                                                    Log.e("EDIT_ERROR", "Error: ${error.message}")
                                                    Log.e("EDIT_ERROR", "Detail: ${error.toString()}")
                                                }
                                            ) {
                                                override fun getParams(): MutableMap<String, String> {

                                                    val params = hashMapOf(
                                                        "id" to item.id.toString(),
                                                        "waktu" to waktu,
                                                        "status" to status
                                                    )

                                                    Log.d("EDIT_PARAMS", params.toString())

                                                    return params
                                                }
                                            }

                                            Volley.newRequestQueue(context).add(request)
                                        },
                                        0, 0, true
                                    ).show()
                                }
                            ) {
                                Icon(
                                    painter = painterResource(id = R.drawable.edit_text),
                                    contentDescription = "Edit",
                                    modifier = Modifier.size(18.dp)
                                )
                            }
                        }

                        // 🔥 tampilkan data
                        Text(
                            text = "${item.waktu} ${item.status}",
                            modifier = Modifier.padding(start = 48.dp)
                                .offset(y = -8.dp)
                        )

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

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

                // ➕ TAMBAH
                item {
                    TextButton(
                        onClick = {
                            TimePickerDialog(
                                context,
                                { _, h, m ->

                                    val status = getWaktuStatus(h, m)
                                    val waktu = String.format("%02d:%02d:00", h, m)

                                    Log.d("TAMBAH_KIRIM", "Waktu: $waktu")
                                    Log.d("TAMBAH_KIRIM", "Status: $status")

                                    val request = object : StringRequest(
                                        Request.Method.POST,
                                        "http://kopikaosmartsystem.my.id/tambah_jadwal.php",

                                        { response ->
                                            Log.d("TAMBAH_SUCCESS", "Response: $response")
                                            loadJadwal()
                                        },

                                        { error ->
                                            Log.e("TAMBAH_ERROR", "Error: ${error.message}")
                                            Log.e("TAMBAH_ERROR", "Detail: ${error.toString()}")
                                        }
                                    ) {
                                        override fun getParams(): MutableMap<String, String> {

                                            val params = hashMapOf(
                                                "waktu" to waktu,
                                                "status" to status
                                            )

                                            Log.d("TAMBAH_PARAMS", params.toString())

                                            return params
                                        }
                                    }

                                    Volley.newRequestQueue(context).add(request)
                                },
                                0, 0, true
                            ).show()
                        }
                    ) {
                        Text("+ Tambah Jadwal")
                    }
                }
            }
        }
    }
}