package com.kaixed.kchat.ui.activity

import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.kaixed.kchat.R
import com.kaixed.kchat.data.objectbox.ObjectBox.get
import com.kaixed.kchat.data.objectbox.entity.Contact
import com.kaixed.kchat.databinding.ActivityMainBinding
import com.kaixed.kchat.ui.base.BaseActivity
import com.kaixed.kchat.ui.fragment.ContactFragment
import com.kaixed.kchat.ui.fragment.DiscoveryFragment
import com.kaixed.kchat.ui.fragment.HomeFragment
import com.kaixed.kchat.ui.fragment.MineFragment
import com.kaixed.kchat.utils.ConstantsUtil.getUsername
import com.kaixed.kchat.utils.ConstantsUtil.isFirstLaunchApp
import com.kaixed.kchat.utils.Pinyin4jUtil
import com.kaixed.kchat.utils.WidgetUtil
import com.kaixed.kchat.viewmodel.ContactViewModel
import io.objectbox.Box
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class MainActivity : BaseActivity<ActivityMainBinding>(), View.OnClickListener {

    private val colorPrimary: Int by lazy { ContextCompat.getColor(this, R.color.green) }
    private val colorBlack: Int by lazy { ContextCompat.getColor(this, R.color.black) }

    private val contactBox: Box<Contact> by lazy { get().boxFor(Contact::class.java) }
    private val contactViewModel: ContactViewModel by viewModels()

    companion object {
        private const val KEY_HOME_FRAGMENT = 0
        private const val KEY_CONTACT_FRAGMENT = 1
        private const val KEY_DISCOVERY_FRAGMENT = 2
        private const val KEY_MINE_FRAGMENT = 3
        private const val TAG = "MainActivity"
    }

    private val fragments = listOf<Fragment>(
        HomeFragment(),
        ContactFragment(),
        DiscoveryFragment(),
        MineFragment()
    )

    private lateinit var viewPagerAdapter: FragmentStateAdapter

    override fun inflateBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        initView()
        initViewPager()
        updateSelection(KEY_HOME_FRAGMENT)
        initData()
    }

    private fun initData() {
        if (isFirstLaunchApp()) {
            lifecycleScope.launch(Dispatchers.Main) {
                val dialog = WidgetUtil.showLoadingDialog(this@MainActivity, "同步数据中")
                dialog.show()
                delay(200)

                contactViewModel.contactListResult.observe(this@MainActivity) { result ->
                    result.onSuccess {
                        contactBox.put(it ?: emptyList())
                    }
                }

                contactViewModel.loadFriendList(getUsername())
                delay(2000)
                dialog.dismiss()
            }
        }
    }

    private fun initView() {
        binding.clHome.setOnClickListener(this)
        binding.clHome.tag = KEY_HOME_FRAGMENT

        binding.clContact.setOnClickListener(this)
        binding.clContact.tag = KEY_CONTACT_FRAGMENT

        binding.clDiscovery.setOnClickListener(this)
        binding.clDiscovery.tag = KEY_DISCOVERY_FRAGMENT

        binding.clMine.setOnClickListener(this)
        binding.clMine.tag = KEY_MINE_FRAGMENT
    }

    private fun initViewPager() {
        // 使用 FragmentStateAdapter 构造函数
        viewPagerAdapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return fragments.size
            }

            override fun createFragment(position: Int): Fragment {
                return fragments[position]
            }
        }
        binding.viewPager.adapter = viewPagerAdapter

        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updateSelection(position)
            }
        })
    }

    override fun onClick(view: View) {
        val key = view.tag as Int
        binding.viewPager.currentItem = key
        updateSelection(key)
    }

    private fun updateSelection(selectedKey: Int) {
        clearSelection()
        when (selectedKey) {
            KEY_HOME_FRAGMENT -> {
                binding.ivHome.isSelected = true
                binding.tvHome.setTextColor(colorPrimary)
            }

            KEY_CONTACT_FRAGMENT -> {
                binding.ivContact.isSelected = true
                binding.tvContact.setTextColor(colorPrimary)
            }

            KEY_DISCOVERY_FRAGMENT -> {
                binding.ivDiscovery.isSelected = true
                binding.tvDiscovery.setTextColor(colorPrimary)
            }

            KEY_MINE_FRAGMENT -> {
                binding.ivMine.isSelected = true
                binding.tvMine.setTextColor(colorPrimary)
            }
        }
    }

    private fun clearSelection() {
        binding.ivHome.isSelected = false
        binding.ivContact.isSelected = false
        binding.ivDiscovery.isSelected = false
        binding.ivMine.isSelected = false

        binding.tvHome.setTextColor(colorBlack)
        binding.tvContact.setTextColor(colorBlack)
        binding.tvDiscovery.setTextColor(colorBlack)
        binding.tvMine.setTextColor(colorBlack)
    }
}
