
package id.ac.ubharajaya.panicbutton

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
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.platform.LocalFocusManager
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody

class MainActivity : ComponentActivity() {

    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private var lastLocation: Location? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        requestLocationPermission()
        getLocation()

        setContent {
            MyApp(
                onClose = { finish() },
                onSend = { report, callback ->
                    val loc = lastLocation
                    val locString = if (loc != null) {
                        "\nLokasi: https://maps.google.com/?q=${loc.latitude},${loc.longitude}"
                    } else {
                        "\nLokasi: Tidak tersedia"
                    }

                    sendNotification(report + locString) { response ->
                        callback(response)

                        // Setelah laporan terkirim, pindah ke pemilihan ruangan
                        startActivity(Intent(this, RuanganActivity::class.java))
                    }
                }
            )
        }
    }

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
            if (granted) getLocation()
        }

    private fun requestLocationPermission() {
        when {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED -> getLocation()

            else -> requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
        }
    }

    private fun getLocation() {
        try {
            fusedLocationClient.lastLocation.addOnSuccessListener { loc: Location? ->
                if (loc != null) lastLocation = loc
            }
        } catch (_: SecurityException) { }
    }
}

// ===========================================================
// UI
// ===========================================================

@Composable
fun MyApp(
    onClose: () -> Unit,
    onSend: (String, (String) -> Unit) -> Unit
) {
    val focusManager = LocalFocusManager.current
    var message by remember { mutableStateOf("Klik tombol untuk mengirim notifikasi") }
    var selectedConditions by remember { mutableStateOf(mutableSetOf<String>()) }
    var additionalNotes by remember { mutableStateOf(TextFieldValue("")) }

    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp)
    ) {

        Text(
            text = "Terjadi Kondisi Darurat:",
            fontSize = 26.sp,
            fontWeight = FontWeight.Bold,
            color = Color.Red
        )

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

        listOf(
            "Kebakaran",
            "Banjir",
            "Tsunami",
            "Gunung Meletus",
            "Gempa Bumi",
            "Huru Hara/Demonstrasi",
            "Binatang Buas",
            "Radiasi Nuklir",
            "Biohazard",
            "Lainnya"
        ).forEach { condition ->
            val emoji = getEmoji(condition)

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable {
                        focusManager.clearFocus()
                        selectedConditions = selectedConditions.toMutableSet().apply {
                            if (contains(condition)) remove(condition) else add(condition)
                        }
                    }
                    .padding(vertical = 3.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Checkbox(
                    checked = selectedConditions.contains(condition),
                    onCheckedChange = { isChecked ->
                        selectedConditions = selectedConditions.toMutableSet().apply {
                            if (isChecked) add(condition) else remove(condition)
                        }
                    }
                )
                Text(text = "$emoji $condition", modifier = Modifier.padding(start = 6.dp))
            }
        }

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

        Text("Catatan tambahan:", fontWeight = FontWeight.Bold)

        BasicTextField(
            value = additionalNotes,
            onValueChange = { additionalNotes = it },
            modifier = Modifier
                .fillMaxWidth()
                .height(100.dp)
                .border(1.dp, Color.Gray)
                .padding(8.dp),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done)
        )

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

        Button(
            onClick = {
                val report =
                    "Kondisi: ${selectedConditions.joinToString()}\nCatatan: ${additionalNotes.text}"
                onSend(report) { msg -> message = msg }
            },
            colors = ButtonDefaults.buttonColors(containerColor = Color.Red)
        ) {
            Text("Kirim Laporan", color = Color.White)
        }

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

        Text(text = message)
        Spacer(modifier = Modifier.height(20.dp))

        Button(onClick = onClose) { Text("Tutup") }
    }
}

// ===========================================================
// Emoji helper
// ===========================================================

fun getEmoji(condition: String): String {
    return when (condition) {
        "Kebakaran" -> "🔥"
        "Banjir" -> "🌊"
        "Tsunami" -> "🌊"
        "Gunung Meletus" -> "🌋"
        "Gempa Bumi" -> "🌎"
        "Huru Hara/Demonstrasi" -> "⚠"
        "Binatang Buas" -> "🐾"
        "Radiasi Nuklir" -> "☢"
        "Biohazard" -> "☣"
        else -> "❗"
    }
}

// ===========================================================
// NOTIFICATION
// ===========================================================

fun sendNotification(report: String, onResult: (String) -> Unit) {
    val client = OkHttpClient()
    val url = "https://ntfy.ubharajaya.ac.id/panic-button"

    val body = RequestBody.create("text/plain".toMediaType(), report)

    val request = Request.Builder()
        .url(url)
        .addHeader("Title", "Alert")
        .addHeader("Priority", "urgent")
        .post(body)
        .build()

    Thread {
        try {
            val response = client.newCall(request).execute()
            if (response.isSuccessful)
                onResult("Notifikasi berhasil dikirim!")
            else
                onResult("Gagal mengirim: ${response.code}")

        } catch (e: Exception) {
            onResult("Error: ${e.message}")
        }
    }.start()
}