package top.yeij.cyrene

import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat
import androidx.navigation.compose.rememberNavController
import org.koin.compose.koinInject
import top.yeij.cyrene.data.local.PreferencesDataStore
import top.yeij.cyrene.service.CyreneVoiceInteractionService
import top.yeij.cyrene.ui.navigation.CyreneNavGraph
import top.yeij.cyrene.ui.navigation.Routes
import top.yeij.cyrene.ui.theme.CyreneTheme
import top.yeij.cyrene.util.Constants

class MainActivity : ComponentActivity() {

    private val isDefaultAssistant = mutableStateOf(false)

    private val notificationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { /* granted or denied — either way we continue */ }

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

        requestNotificationPermission()
        isDefaultAssistant.value = checkIsDefaultAssistant()

        setContent {
            val prefs: PreferencesDataStore = koinInject()
            val themeMode by prefs.themeMode.collectAsState(initial = null)
            val themeColor by prefs.themeColor.collectAsState(initial = "pink")
            val darkTheme = when (themeMode) {
                "light" -> false
                "dark" -> true
                else -> isSystemInDarkTheme()
            }
            val useDynamic = themeColor == "monet" && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S

            CyreneTheme(
                darkTheme = darkTheme,
                presetKey = themeColor,
                useDynamicColor = useDynamic,
            ) {
                val navController = rememberNavController()

                CyreneNavGraph(
                    navController = navController,
                    startDestination = Routes.MAIN,
                    isDefaultAssistant = isDefaultAssistant.value,
                    onOpenAssistantSettings = { openAssistantSettings() },
                )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        isDefaultAssistant.value = checkIsDefaultAssistant()
    }

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

    private fun checkIsDefaultAssistant(): Boolean {
        // Standard Android check
        val flat = ComponentName(this, CyreneVoiceInteractionService::class.java).flattenToString()
        val current = Settings.Secure.getString(contentResolver, "voice_interaction_service")
        if (current == flat) return true
        // Fallback for COS and other custom OS: check persisted flag from service
        if (CyreneVoiceInteractionService.wasEverActive(this)) return true
        return false
    }

    private fun openAssistantSettings() {
        startActivity(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS))
    }

    private fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                != PackageManager.PERMISSION_GRANTED
            ) {
                notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }
}
