package id.ac.ubharajaya.panicbutton

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.compose.material3.MaterialTheme
import com.google.android.gms.location.LocationServices
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    private lateinit var viewModel: MainViewModel

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            // result handled inline when requesting
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        val fusedClient = LocationServices.getFusedLocationProviderClient(this)

        val openEvacMaps = {
            startActivity(Intent(this, EvacuationMapsActivity::class.java))
        }

        // onSendAlert will try to get location (if permission granted) and then call viewModel.sendAlert
        val onSendAlert = {
            // Check permission
            val fineGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            val coarseGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED

            if (!fineGranted && !coarseGranted) {
                // Request fine location permission (preferred)
                requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
                // After permission flow, user will need to press the button again to actually send with location
                viewModel.dialogMessage = "Izin lokasi dibutuhkan untuk menyertakan koordinat. Silakan tekan lagi setelah mengizinkan lokasi."
                return@let
            }

            // Try get last location asynchronously
            CoroutineScope(Dispatchers.Main).launch {
                try {
                    val loc = fusedClient.lastLocation.await() // need extension await - we'll handle fallback
                    if (loc != null) {
                        viewModel.sendAlert(loc.latitude, loc.longitude)
                    } else {
                        // fallback: send without coordinates
                        viewModel.sendAlert()
                    }
                } catch (e: Exception) {
                    viewModel.sendAlert()
                }
            }
        }

        setContent {
            MaterialTheme {
                MainScreen(viewModel = viewModel, onOpenEvacMaps = openEvacMaps)
            }
        }
    }
}