package com.gallery.free.wallpaper

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.gallery.free.wallpaper.databinding.ActivityMainBinding
import com.gallery.free.wallpaper.fragment.ColleFragment
import com.gallery.free.wallpaper.fragment.HoFragment
import com.gallery.free.wallpaper.fragment.SeFragment
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {
    private lateinit var vb: ActivityMainBinding

    // 保存 Fragment 实例和状态
    private var homeFragment: HoFragment? = null
    private var collectionFragment: ColleFragment? = null
    private var settingFragment: SeFragment? = null
    private var currentFragmentTag: String = "home"

    // 添加协程作用域
    private val activityScope = CoroutineScope(Dispatchers.Main + Job())

    companion object {
        private const val KEY_CURRENT_FRAGMENT = "current_fragment"
        private const val TAG_HOME = "home"
        private const val TAG_COLLECTION = "collection"
        private const val TAG_SETTING = "setting"
        const val PERMISSION_GALLERY_REQUEST_CODE = 1002
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vb = ActivityMainBinding.inflate(layoutInflater)
        Utils_com.initFull(this, true)
        setContentView(vb.root)

        // 初始化 Application 数据
        initApplicationData()

        // 恢复状态
        if (savedInstanceState != null) {
            currentFragmentTag = savedInstanceState.getString(KEY_CURRENT_FRAGMENT, TAG_HOME)
            // 恢复 Fragment 实例
            homeFragment = supportFragmentManager.findFragmentByTag(TAG_HOME) as? HoFragment
            collectionFragment = supportFragmentManager.findFragmentByTag(TAG_COLLECTION) as? ColleFragment
            settingFragment = supportFragmentManager.findFragmentByTag(TAG_SETTING) as? SeFragment
        }

        setupBottomNavigation()
        checkIfShouldShowSettingFragment()

        // 显示初始 Fragment
        if (savedInstanceState == null) {
            showFragment(currentFragmentTag)
        } else {
            showFragment(currentFragmentTag)
        }
    }
    private fun checkIfShouldShowSettingFragment() {
        intent?.let { intent ->
            if (intent.hasExtra("SHOW_SETTING_FRAGMENT")) {
                Log.d("MainActivity", "接收到SHOW_SETTING_FRAGMENT标志，显示SettingFragment")
                currentFragmentTag = TAG_SETTING
                updateBottomNavigation(2)  // 选中设置按钮
                intent.removeExtra("SHOW_SETTING_FRAGMENT")  // 清除标志
            }
        }
    }
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        Log.d("MainActivity", "onNewIntent被调用")

        // ✅ 处理从预览页面返回的情况
        this.intent = intent
        checkIfShouldShowSettingFragment()
    }
    /**
     * 初始化 Application 数据
     */
    private fun initApplicationData() {
        activityScope.launch {
            try {
                withContext(Dispatchers.IO) {
                }

                // 获取 Application 实例
                val myApp = application as? MyApplication
                myApp?.let {
                    Log.d("MainActivity", "Application 数据初始化完成")
                }
            } catch (e: Exception) {
                Log.e("MainActivity", "Application 数据初始化失败", e)
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString(KEY_CURRENT_FRAGMENT, currentFragmentTag)
    }

    private fun setupBottomNavigation() {
        // 设置首页按钮选中状态
        updateBottomNavigation(0)

        // 首页按钮点击
        vb.homeLayout.setOnClickListener {
            showFragment(TAG_HOME)
            updateBottomNavigation(0)
        }

        // 收藏按钮点击
        vb.collectionLayout.setOnClickListener {
            showFragment(TAG_COLLECTION)
            updateBottomNavigation(1)
        }

        // 设置按钮点击
        vb.settingsLayout.setOnClickListener {
            showFragment(TAG_SETTING)
            updateBottomNavigation(2)
        }
    }

    private fun updateBottomNavigation(selectedPosition: Int) {
        // 重置所有按钮状态
        vb.homeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.white))
        vb.collectionLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.white))
        vb.settingsLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.white))

        vb.homeIcon.setImageResource(R.drawable.ic_home_disabled)
        vb.collectionIcon.setImageResource(R.drawable.ic_collection_disabled)
        vb.settingsIcon.setImageResource(R.drawable.ic_settings_disabled)

        // 设置选中按钮状态
        when (selectedPosition) {
            0 -> {
                vb.homeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_purple))
                vb.homeIcon.setImageResource(R.drawable.ic_home)
            }
            1 -> {
                vb.collectionLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_purple))
                vb.collectionIcon.setImageResource(R.drawable.ic_collection)
            }
            2 -> {
                vb.settingsLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_purple))
                vb.settingsIcon.setImageResource(R.drawable.ic_settings)
            }
        }
    }

    private fun showFragment(tag: String) {
        Log.d("MainActivity", "显示Fragment: $tag")

        currentFragmentTag = tag

        val transaction = supportFragmentManager.beginTransaction()

        // 隐藏所有 Fragment
        homeFragment?.let { transaction.hide(it) }
        collectionFragment?.let { transaction.hide(it) }
        settingFragment?.let { transaction.hide(it) }

        when (tag) {
            TAG_HOME -> {
                if (homeFragment == null) {
                    homeFragment = HoFragment.newInstance()
                    transaction.add(R.id.fragment_container, homeFragment!!, TAG_HOME)
                } else {
                    transaction.show(homeFragment!!)
                }
            }
            TAG_COLLECTION -> {
                if (collectionFragment == null) {
                    collectionFragment = ColleFragment.newInstance()
                    transaction.add(R.id.fragment_container, collectionFragment!!, TAG_COLLECTION)
                } else {
                    transaction.show(collectionFragment!!)
                }
            }
            TAG_SETTING -> {
                if (settingFragment == null) {
                    settingFragment = SeFragment.newInstance()
                    transaction.add(R.id.fragment_container, settingFragment!!, TAG_SETTING)
                } else {
                    transaction.show(settingFragment!!)
                }
            }
        }

        transaction.commit()
    }

    /**
     * 获取应用实例
     */
    fun getMyApplication(): MyApplication? {
        return application as? MyApplication
    }

    // 处理权限请求结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        // 将权限结果传递给当前显示的Fragment
        when (currentFragmentTag) {
            TAG_SETTING -> {
                settingFragment?.onRequestPermissionsResult(requestCode, permissions, grantResults)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 取消所有协程
        activityScope.coroutineContext.cancelChildren()
    }
}