package id.ac.ubharajaya.panicbutton

import androidx.compose.runtime.*
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

// Ganti ReportOption dengan EmergencyOption
data class EmergencyOption(
    val label: String,
    val icon: String
)

class MainViewModel : ViewModel() {
    val options = listOf(
        EmergencyOption("Kebakaran", "🔥"),
        EmergencyOption("Banjir", "🌊"),
        EmergencyOption("Gempa Bumi", "🌍"),
        EmergencyOption("Huru Hara/Demonstrasi", "💥"),
        EmergencyOption("Lainnya", "✏️")
    )

    // observable map so Compose recomposes on changes
    private val _checkedState = mutableStateMapOf<String, Boolean>().apply {
        options.forEach { put(it.label, false) }
    }

    var otherNote by mutableStateOf("")
    var dialogMessage by mutableStateOf<String?>(null)

    fun isChecked(label: String): Boolean = _checkedState[label] == true

    fun setChecked(label: String, isChecked: Boolean) {
        _checkedState[label] = isChecked
        // Clear otherNote jika "Lainnya" di-uncheck
        if (label == "Lainnya" && !isChecked) {
            otherNote = ""
        }
    }

    // latitude/longitude optional parameters
    fun sendAlert(latitude: Double? = null, longitude: Double? = null) {
        val selectedOptions = options.filter { isChecked(it.label) }.map { it.label }

        if (selectedOptions.isEmpty()) {
            dialogMessage = "Pilih setidaknya satu kondisi darurat."
            return
        }

        if (isChecked("Lainnya") && otherNote.isBlank()) {
            dialogMessage = "Catatan wajib diisi jika Anda memilih 'Lainnya'."
            return
        }

        // Build message payload
        val bodyBuilder = StringBuilder()
        bodyBuilder.append("Kondisi: ${selectedOptions.joinToString(", ")}")
        if (otherNote.isNotBlank()) {
            bodyBuilder.append("\nCatatan: ${otherNote.trim()}")
        }

        // Append coordinates if available
        if (latitude != null && longitude != null) {
            bodyBuilder.append("\nLokasi: https://maps.google.com/?q=$latitude,$longitude")
        }

        val payload = bodyBuilder.toString()

        // Use NotificationSender utility to send the payload
        viewModelScope.launch {
            try {
                val resultMessage = NotificationSender.sendNotification(payload)
                dialogMessage = resultMessage
            } catch (e: Exception) {
                e.printStackTrace()
                dialogMessage = "Gagal mengirim laporan. Silakan periksa koneksi Anda dan coba lagi."
            }
        }
    }

    fun clearDialog() {
        dialogMessage = null
    }
}