package com.example.uitugasakhir.aksi

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley

@Composable
fun DeleteDialog(
    showDialog: Boolean,
    selectedId: String,
    context: Context,
    onDismiss: () -> Unit,
    onSuccess: () -> Unit
) {

    if (!showDialog) return

    AlertDialog(
        onDismissRequest = { onDismiss() },

        title = {
            Text("Konfirmasi")
        },

        text = {
            Text("Yakin ingin menghapus jadwal ini?")
        },

        confirmButton = {
            TextButton(
                onClick = {

                    Log.d("DELETE", "HAPUS ID: $selectedId")

                    val request = object : StringRequest(
                        Request.Method.POST,
                        "http://kopikaosmartsystem.my.id/hapus_jadwal.php",
                        { response ->
                            Log.d("API", "Response: $response")
                            Toast.makeText(context, "Berhasil dihapus", Toast.LENGTH_SHORT).show()

                            onDismiss()
                            onSuccess() // refresh data
                        },
                        { error ->
                            Log.e("API", error.toString())
                            Toast.makeText(context, "Gagal hapus", Toast.LENGTH_SHORT).show()
                        }
                    ) {
                        override fun getParams(): MutableMap<String, String> {
                            return hashMapOf("id" to selectedId)
                        }
                    }

                    Volley.newRequestQueue(context).add(request)
                }
            ) {
                Text("OK")
            }
        },

        dismissButton = {
            TextButton(
                onClick = { onDismiss() }
            ) {
                Text("Batal")
            }
        }
    )
}