package com.tsmobile.app

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.rememberNavController
import com.tsmobile.app.ui.navigation.AppNavGraph
import com.tsmobile.app.ui.theme.TSMobileTheme
import com.tsmobile.app.viewmodel.ServerViewModel
import com.tsmobile.app.viewmodel.VoiceViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class MainActivity : ComponentActivity() {

    companion object {
        /** Intent extra: deep link target route ("chat" or "channel_list") */
        const val EXTRA_DEEP_LINK = "deep_link"
        const val DEEP_LINK_CHAT = "chat"
        const val DEEP_LINK_CHANNEL_LIST = "channel_list"
        /** Intent extra: 消息的 targetMode（2=频道，1=私聊） */
        const val EXTRA_TARGET_MODE = "target_mode"
        /** Intent extra: 消息的 targetId（频道 ID 或客户端 ID） */
        const val EXTRA_TARGET_ID = "target_id"
    }

    /** 系统通知点击产生的导航目标 */
    data class DeepLinkAction(
        val target: String,
        val targetMode: Int? = null,
        val targetId: Long? = null,
    )

    private val _deepLinkAction = MutableStateFlow<DeepLinkAction?>(null)
    val deepLinkAction: StateFlow<DeepLinkAction?> = _deepLinkAction.asStateFlow()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 处理冷启动时的 deep link（app 进程被杀后通过通知重新启动）
        processIntent(intent)
        enableEdgeToEdge()
        setContent {
            val serverViewModel: ServerViewModel = viewModel()
            val voiceViewModel: VoiceViewModel = viewModel()
            val themeMode by serverViewModel.themeMode.collectAsState()
            val permissionLauncher = rememberLauncherForActivityResult(
                contract = ActivityResultContracts.RequestMultiplePermissions(),
            ) { result ->
                if (result[Manifest.permission.RECORD_AUDIO] == true) {
                    voiceViewModel.onPermissionGranted()
                }
            }

            LaunchedEffect(Unit) {
                val permissions = buildList {
                    if (ContextCompat.checkSelfPermission(
                            this@MainActivity,
                            Manifest.permission.RECORD_AUDIO,
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        add(Manifest.permission.RECORD_AUDIO)
                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
                        ContextCompat.checkSelfPermission(
                            this@MainActivity,
                            Manifest.permission.POST_NOTIFICATIONS,
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        add(Manifest.permission.POST_NOTIFICATIONS)
                    }
                }
                if (permissions.isNotEmpty()) {
                    permissionLauncher.launch(permissions.toTypedArray())
                }
            }

            TSMobileTheme(themeMode = themeMode) {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background,
                ) {
                    val navController = rememberNavController()

                    AppNavGraph(
                        navController = navController,
                        serverViewModel = serverViewModel,
                        voiceViewModel = voiceViewModel,
                        deepLinkAction = deepLinkAction,
                        onDeepLinkConsumed = { _deepLinkAction.value = null },
                    )
                }
            }
        }
    }

    /**
     * 用户从后台通过通知回到 app 时调用。
     * 因为 [android.app.PendingIntent] 使用了 FLAG_ACTIVITY_SINGLE_TOP，
     * 已存在的 Activity 不会重建，而是通过此方法接收新的 Intent。
     */
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        processIntent(intent)
    }

    /**
     * 每次 Activity 回到前台时清除消息/Poke 通知。
     * 防止用户手动切回 app 后频道变化，旧通知中的 deep link 指向错误频道。
     */
    override fun onResume() {
        super.onResume()
        try {
            ViewModelProvider(this)[ServerViewModel::class.java].clearNotifications()
        } catch (_: Exception) {}
    }

    /**
     * 从 Intent 中提取 deep link 信息并更新 StateFlow，
     * 触发 NavGraph 的导航逻辑。
     */
    private fun processIntent(intent: Intent?) {
        val target = intent?.getStringExtra(EXTRA_DEEP_LINK) ?: return
        val targetMode = intent.getIntExtra(EXTRA_TARGET_MODE, -1).takeIf { it >= 0 }
        val targetId = intent.getLongExtra(EXTRA_TARGET_ID, -1L).takeIf { it >= 0L }
        _deepLinkAction.value = DeepLinkAction(target, targetMode, targetId)
    }
}

