package com.example.myapplication

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import com.example.myapplication.network.AuthEventBus
import com.example.myapplication.network.AuthEvent
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private lateinit var bottomNav: BottomNavigationView
    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        lifecycleScope.launch {
            AuthEventBus.events.collectLatest { event ->
                if (event is AuthEvent.TokenExpired) {
                    val navController = (supportFragmentManager
                        .findFragmentById(R.id.nav_host_fragment) as NavHostFragment)
                        .navController
        
                    // 避免重复跳转（比如已经在登录页）
                    if (navController.currentDestination?.id != R.id.loginFragment) {
                        navController.navigate(R.id.action_global_loginFragment)
                    }
                } else if (event is AuthEvent.GenericError) {
                    android.widget.Toast.makeText(this@MainActivity, "${event.message}", android.widget.Toast.LENGTH_SHORT).show()
                }
            }
        }

        // 1. 找到 NavHostFragment
        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController = navHostFragment.navController

        // 2. 找到 BottomNavigationView
        bottomNav = findViewById(R.id.bottom_nav)

        // 3. 绑定导航控制器（负责切换 Fragment、保持选中状态）
        bottomNav.setupWithNavController(navController)

        // 4. 取消图标颜色 tint —— 使用原图标颜色
        bottomNav.itemIconTintList = null

        // 5. 添加导航监听（用于某些 Fragment 隐藏底部导航栏）
        navController.addOnDestinationChangedListener { _, destination, _ ->

            // 只有这些页面显示 BottomNav
            val pagesWithBottomNav = setOf(
                R.id.mineFragment,
                R.id.homeFragment,
                R.id.shopFragment
            )
        
            if (destination.id in pagesWithBottomNav) {
                bottomNav.visibility = View.VISIBLE
            } else {
                bottomNav.visibility = View.GONE
            }
        }
        

        // 6. 检查是否有导航参数，处理从键盘跳转过来的请求
        handleNavigationFromIntent()
    }

    private fun handleNavigationFromIntent() {
        val navigateTo = intent.getStringExtra("navigate_to")
        if (navigateTo == "recharge_fragment") {
            // 延迟执行导航，确保导航控制器已经准备好
            bottomNav.post {
                try {
                    navController.navigate(R.id.action_global_rechargeFragment)
                } catch (e: Exception) {
                    // 如果导航失败，记录错误日志
                    android.util.Log.e("MainActivity", "Failed to navigate to recharge fragment", e)
                }
            }
        }
    }
}
