package com.aiosman.riderpro

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.runtime.compositionLocalOf
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.navigation.NavHostController
import cn.jiguang.api.utils.JCollectionAuth
import cn.jpush.android.api.JPushInterface
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.UserService
import com.aiosman.riderpro.data.UserServiceImpl
import com.aiosman.riderpro.ui.Navigation
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.navigateToPost
import com.aiosman.riderpro.ui.post.NewPostViewModel
import com.google.firebase.analytics.FirebaseAnalytics
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class MainActivity : ComponentActivity() {
    // Firebase Analytics
    private lateinit var analytics: FirebaseAnalytics
    private val scope = CoroutineScope(Dispatchers.Main)

    // 请求通知权限
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission(),
    ) { isGranted: Boolean ->
        if (isGranted) {
            // FCM SDK (and your app) can post notifications.
        } else {

        }
    }

    /**
     * 获取账号信息
     */
    private suspend fun getAccount(): Boolean {
        val accountService: AccountService = AccountServiceImpl()
        try {
            val resp = accountService.getMyAccount()
            return true
        } catch (e: Exception) {
            return false
        }
    }

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

        // 监听应用生命周期
        ProcessLifecycleOwner.get().lifecycle.addObserver(MainActivityLifecycleObserver())

        // 创建通知渠道
        createNotificationChannel()

        // 沉浸式状态栏
        WindowCompat.setDecorFitsSystemWindows(window, false)

        // 请求通知权限
        askNotificationPermission()

        // 加载一些本地化的配置
        AppStore.init(this)

        enableEdgeToEdge()

        setContent {
            // 根据登录状态决定启动页面
            val startDestination = if (AppStore.isLoggedIn) {
                NavigationRoute.Index.route
            } else {
                NavigationRoute.Login.route
            }

            Navigation(startDestination) { navController ->
                // 处理带有 postId 的通知点击
                val postId = intent.getStringExtra("POST_ID")
                var commentId = intent.getStringExtra("COMMENT_ID")
                val action = intent.getStringExtra("ACTION")
                if (action == "newFollow") {
                    navController.navigate(NavigationRoute.Followers.route)
                    return@Navigation
                }
                if (action == "followCount") {
                    navController.navigate(NavigationRoute.Followers.route)
                    return@Navigation
                }
                if (action == "TRTC_NEW_MESSAGE") {
                    val userService: UserService = UserServiceImpl()
                    val sender = intent.getStringExtra("SENDER")
                    sender?.let {
                        scope.launch {
                            try {
                                val profile = userService.getUserProfileByTrtcUserId(it)
                                navController.navigate(
                                    NavigationRoute.Chat.route.replace(
                                        "{id}",
                                        profile.id.toString()
                                    )
                                )
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                    return@Navigation
                }

                if (commentId == null) {
                    commentId = "0"
                }

                if (postId != null) {
                    Log.d("MainActivity", "Navigation to Post$postId")
                    navController.navigateToPost(
                        id = postId.toInt(),
                        highlightCommentId = commentId.toInt(),
                        initImagePagerIndex = 0
                    )
                }
                // 处理分享过来的图片
                if (intent?.action == Intent.ACTION_SEND || intent?.action == Intent.ACTION_SEND_MULTIPLE) {
                    val imageUris: List<Uri>? = if (intent.action == Intent.ACTION_SEND) {
                        listOf(intent.getParcelableExtra(Intent.EXTRA_STREAM)!!)
                    } else {
                        intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM)
                    }
                    NewPostViewModel.asNewPostWithImageUris(imageUris!!.map { it.toString() })
                    navController.navigate(NavigationRoute.NewPost.route)

                }
            }
        }
    }
    /**
     * 请求通知权限
     */
    private fun askNotificationPermission() {
        // This is only necessary for API level >= 33 (TIRAMISU)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
                PackageManager.PERMISSION_GRANTED
            ) {
                // FCM SDK (and your app) can post notifications.
            } else if (shouldShowRequestPermissionRationale(android.Manifest.permission.POST_NOTIFICATIONS)) {

            } else {
                // Directly ask for the permission
                requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }

    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = ConstVars.MOMENT_LIKE_CHANNEL_ID
            val channelName = ConstVars.MOMENT_LIKE_CHANNEL_NAME
            val channel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
}

val LocalNavController = compositionLocalOf<NavHostController> {
    error("NavController not provided")
}

@OptIn(ExperimentalSharedTransitionApi::class)
val LocalSharedTransitionScope = compositionLocalOf<SharedTransitionScope> {
    error("SharedTransitionScope not provided")
}

val LocalAnimatedContentScope = compositionLocalOf<AnimatedContentScope> {
    error("AnimatedContentScope not provided")
}


