package id.ac.ubharajaya.panicbutton

import android.Manifest
import android.annotation.SuppressLint
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

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

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            if (isGranted) {
                if (::viewModel.isInitialized) viewModel.dialogMessage = "Izin lokasi diberikan. Tekan kembali untuk menyertakan koordinat."
            } else {
                if (::viewModel.isInitialized) viewModel.dialogMessage = "Izin lokasi ditolak. Laporan akan dikirim tanpa koordinat."
            }
        }

    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))
        }

        @SuppressLint("MissingPermission")
        fun handleSendAlert() {
            // 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) {
                requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
                viewModel.dialogMessage = "Izin lokasi dibutuhkan untuk menyertakan koordinat. Silakan tekan lagi setelah mengizinkan lokasi."
                return
            }
            
            fusedClient.lastLocation
                .addOnSuccessListener { loc ->
                    if (loc != null) {
                        viewModel.sendAlert(loc.latitude, loc.longitude)
                    } else {
                        viewModel.sendAlert()
                    }
                }
                .addOnFailureListener {
                    viewModel.sendAlert()
                }
        }

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