package com.adealink.weparty.playmate.list

import android.os.Bundle
import android.util.TypedValue
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.adealink.frame.aab.util.getCompatColor
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.recycleview.adapter.BaseTabFragmentStateAdapter
import com.adealink.weparty.databinding.LayoutHomeTabBinding
import com.adealink.weparty.module.playmate.Playmate
import com.adealink.weparty.module.playmate.data.PlaymateCategoryData
import com.adealink.weparty.playmate.R
import com.adealink.weparty.playmate.databinding.FragmentPlaymateHomeBinding
import com.adealink.weparty.playmate.viewmodel.PlaymateViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

@RouterUri(path = [Playmate.Home.PATH], desc = "陪玩首页")
class PlaymateHomeFragment : BaseFragment(R.layout.fragment_playmate_home) {

    override val isLazyInit: Boolean = true
    override val isLazyLoad: Boolean = true
    private val binding by viewBinding(FragmentPlaymateHomeBinding::bind)
    private lateinit var pageAdapter: PageAdapter
    private val playmateViewModel by activityViewModels<PlaymateViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Router.bind(this)
    }

    override fun initViews() {
        super.initViews()
        //主内容
        initHomeTabs()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        playmateViewModel.allCategoryLD.observe(viewLifecycleOwner) {
            val onlineList = mutableListOf<PlaymateCategoryData>()
            val activityList = mutableListOf<PlaymateCategoryData>()
            for (entry in it.entries) {
                if (entry.value.isActivity()) {
                    activityList.add(entry.value)
                } else {
                    onlineList.add(entry.value)
                }
            }
            val categoryList = mutableListOf<PlaymateCategoryData>()
            onlineList.take(2).let { list ->
                categoryList.addAll(list)
            }
            activityList.take(1).let { list ->
                categoryList.addAll(list)
            }
            pageAdapter.setCategory(categoryList)
        }
    }

    override fun loadData() {
        playmateViewModel.pullAllCategory()
    }

    private fun initHomeTabs() {
        pageAdapter = PageAdapter()
        binding.vpContent.offscreenPageLimit = 1
        binding.vpContent.adapter = pageAdapter
        binding.vpContent.isSaveEnabled = false
        TabLayoutMediator(
            binding.tlTab,
            binding.vpContent,
            true,
            false
        ) { tabLayout, position ->
            tabLayout.setCustomView(com.adealink.weparty.R.layout.layout_home_tab)
            tabLayout.customView?.let { tabView ->
                val tabViewBinding = LayoutHomeTabBinding.bind(tabView)
                onConfigureTab(tabViewBinding, position)
                updateTabView(
                    tabLayout,
                    0 == position
                )
            }
        }.attach()
        binding.tlTab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {
                updateTabView(tab, true)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                updateTabView(tab, false)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })
    }

    private fun onConfigureTab(binding: LayoutHomeTabBinding, position: Int) {
        binding.tvTab.text = pageAdapter.getTabName(position)
    }

    private fun updateTabView(
        tabView: TabLayout.Tab?,
        isSelected: Boolean
    ) {
        tabView?.customView?.let { tabView ->
            val tabViewBinding = LayoutHomeTabBinding.bind(tabView)
            if (isSelected) {
                tabViewBinding.ivTabBg.show()
                tabViewBinding.tvTab.setTextColor(getCompatColor(com.adealink.weparty.R.color.color_FF1D2129))
                tabViewBinding.tvTab.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22f)
            } else {
                tabViewBinding.ivTabBg.gone()
                tabViewBinding.tvTab.setTextColor(getCompatColor(com.adealink.weparty.R.color.color_FF4E5969))
                tabViewBinding.tvTab.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
            }
        }
    }

    data class PageData(
        val data: PlaymateCategoryData,
        val pageId: Long
    )

    internal inner class PageAdapter : BaseTabFragmentStateAdapter(this) {

        private val pages = mutableListOf<PageData>()

        fun setCategory(category: List<PlaymateCategoryData>) {
            pages.clear()
            pages.addAll(category.map {
                PageData(it, it.code.hashCode().toLong())
            })
            notifyDataSetChanged()
        }

        override fun getItemId(position: Int): Long {
            val hash = pages.getOrNull(position)?.pageId ?: 0L
            return hash
        }

        override fun containsItem(itemId: Long): Boolean {
            return super.containsItem(itemId)
        }

        override fun getTabName(pos: Int): String {
            return pages.getOrNull(pos)?.data?.name ?: ""
        }

        override fun getItemCount(): Int {
            return pages.size
        }

        override fun createFragment(position: Int): Fragment {
            val categoryData = pages.getOrNull(position)
            return PlaymateHomeListFragment().apply {
                arguments = Bundle().apply {
                    categoryData?.let { data ->
                        putParcelable(Playmate.Common.EXTRA_CATEGORY, data.data)
                    }
                }
            }
        }

    }

}