package com.jishisongfu.duobibi

import android.Manifest
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.result.contract.ActivityResultContracts
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import com.jishisongfu.duobibi.auth.JgInit
import com.jishisongfu.duobibi.data.repo.PriceRepository
import com.jishisongfu.duobibi.heartbeat.HeartbeatScheduler
import com.jishisongfu.duobibi.heartbeat.HeartbeatSender
import com.jishisongfu.duobibi.push.MiPushBootstrap
import com.jishisongfu.duobibi.ui.nav.AppNavHost
import com.jishisongfu.duobibi.ui.onboarding.OnboardingScreen
import com.jishisongfu.duobibi.ui.privacy.PrivacyConsentScreen
import com.jishisongfu.duobibi.ui.theme.DuobibiTheme
import com.jishisongfu.duobibi.util.AlertNotifier
import com.jishisongfu.duobibi.util.DemoDataSeeder
import com.jishisongfu.duobibi.util.FloatingServiceLauncher
import com.jishisongfu.duobibi.util.OnboardingPrefs
import com.jishisongfu.duobibi.util.PrivacyPrefs
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    @Inject lateinit var repository: PriceRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DuobibiTheme {
                var agreed by remember { mutableStateOf(PrivacyPrefs.agreed(this)) }
                var onboarded by remember { mutableStateOf(OnboardingPrefs.completed(this)) }

                val notificationLauncher = rememberLauncherForActivityResult(
                    ActivityResultContracts.RequestPermission(),
                ) { /* 不论结果都不阻塞流程 */ }

                LaunchedEffect(agreed) {
                    if (agreed && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        val granted = ContextCompat.checkSelfPermission(
                            this@MainActivity, Manifest.permission.POST_NOTIFICATIONS,
                        ) == PackageManager.PERMISSION_GRANTED
                        if (!granted) notificationLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
                    }
                    if (agreed) {
                        ioScope.launch { DemoDataSeeder.seedIfNeeded(applicationContext, repository) }
                    }
                }

                when {
                    !agreed -> PrivacyConsentScreen(
                        onAgree = {
                            PrivacyPrefs.setAgreed(this, true)
                            agreed = true
                            FloatingServiceLauncher.startIfReady(this)
                            // 首启同意隐私后立刻补 register/init(Application.onCreate 已跑完不会再触发)
                            MiPushBootstrap.registerIfReady(this)
                            JgInit.initIfReady(this)
                            HeartbeatScheduler.start(this)
                            ioScope.launch { HeartbeatSender.send(applicationContext, "privacy_agree") }
                        },
                        onReject = { finish() },
                    )
                    !onboarded -> OnboardingScreen(
                        onFinish = {
                            OnboardingPrefs.setCompleted(this, true)
                            onboarded = true
                        },
                    )
                    else -> AppNavHost()
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        FloatingServiceLauncher.startIfReady(this)
        if (PrivacyPrefs.agreed(this)) {
            ioScope.launch { HeartbeatSender.send(applicationContext, "onResume") }
            // 降价雷达批量查价(MVP 用 onResume 触发代替 WorkManager)。到价的发本地通知。
            ioScope.launch {
                try {
                    val triggered = repository.batchCheckAlerts()
                    if (triggered.isNotEmpty()) AlertNotifier.notifyTriggered(applicationContext, triggered)
                } catch (_: Exception) {
                    // 网络挂时静默,下次 onResume 再试
                }
            }
        }
    }
}
