package com.example.uitugasakhir

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.*
import kotlinx.coroutines.delay
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.compose.animation.*
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.uitugasakhir.Page.NotifikasiScreen
import com.example.uitugasakhir.ViewModel.MainViewModel
import android.content.Intent
import androidx.compose.ui.platform.LocalContext
import com.example.uitugasakhir.ViewModel.SensorViewModel
import android.os.Build
import androidx.activity.result.contract.ActivityResultContracts
import com.example.uitugasakhir.model.AlertEvent
import android.util.Log




class MainActivity : ComponentActivity() {

    private var pendingRoute: String? = null

    private val requestPermissionLauncher =
        registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                startSensorService()
            }
        }

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
        } else {
            startSensorService()
        }

        handleIntent(intent)

        setContent {

            val mainVm: MainViewModel = viewModel()

            AppNavigation(
                routeFromNotif = pendingRoute,
                mainVm = mainVm
            )
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        handleIntent(intent)
    }

    private fun handleIntent(intent: Intent) {
        pendingRoute = intent.getStringExtra("route")
    }

    private fun startSensorService() {
        val serviceIntent = Intent(this, SensorMonitoringService::class.java)
    }
}


@Composable
fun AppNavigation(
    routeFromNotif: String?,
    mainVm: MainViewModel
) {

    val context = LocalContext.current

    val sensorVm: SensorViewModel = viewModel()

    LaunchedEffect(Unit) {

        sensorVm.loadUnreadCount()
    }

    var showSplash by remember { mutableStateOf(!AppSession.isSplashShown) }

    val navController = rememberNavController()

    var navReady by remember { mutableStateOf(false) }

    val alert = mainVm.alertEvent

    var showPopupState = remember { mutableStateOf<AlertEvent?>(null) }

    LaunchedEffect(Unit) {
        mainVm.alertEvent.collect { event ->

            Log.d("ALERT_FLOW", "UI RECEIVED ALERT → ${event.title}")


            SensorNotification.showNotification(
                context,
                event.title,
                event.message
            )
        }
    }

    LaunchedEffect(Unit) {
        delay(3000)
        showSplash = false
        AppSession.isSplashShown = true
    }

    if (showSplash) {
        SplashScreen()
        return
    }

    LaunchedEffect(Unit) {
        navReady = true
    }

    LaunchedEffect(routeFromNotif, navReady) {
        if (navReady) {
            routeFromNotif?.let {
                navController.navigate(it) {
                    launchSingleTop = true
                }
            }
        }
    }

    NavHost(
        navController = navController,
        startDestination = "dashboard"
    ) {

        composable("manual") {
            ManualScreen(
                navController = navController,
                sensorVm = sensorVm,
                mainVm = mainVm
            )
        }

        composable("notifikasi") {
            NotifikasiScreen(
                navController = navController,
                sensorVm = sensorVm
            )
        }

        composable("dashboard") {

            DashboardScreen(
                navController = navController,
                sensorVm = sensorVm,
                mainVm = mainVm
            )
        }

        composable("pengaturan") {
            PengaturanScreen(navController)
        }

        composable("riwayat") {
            RiwayatScreen(navController)
        }

        composable("login") {
            LoginScreen(navController)
        }

        composable("register") {
            RegisterScreen(navController)
        }

        composable("forgot_password") {
            ForgotPasswordScreen(navController)
        }

        composable("panduan") {
            PanduanScreen(navController)
        }
    }
}