package com.gh.gamecenter.gamecollection.choose

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.FragmentHotGamesBinding
import com.gh.gamecenter.entity.SubjectData
import com.gh.gamecenter.entity.SubjectEntity
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class AddHotGamesFragment: BaseFragment<Any>() {
    private val binding by lazy { FragmentHotGamesBinding.inflate(layoutInflater, null, false) }
    private val viewModel: AddHotGamesViewModel by lazy { viewModelProvider() }
    private var adapter: FragmentStateAdapter? = null
    private val tabEntityList = arrayListOf<SubjectEntity>()

    override fun getLayoutId(): Int = 0
    override fun getInflatedLayout(): View = binding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            tabContainer.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
            reuseNoConnection.connectionReloadTv.setOnClickListener {
                reuseNoConnection.root.visibility = View.GONE
                viewModel.getHotColumns()
            }
        }

        viewModel.tabListLiveData.observe(viewLifecycleOwner) {
            if (it != null) {
                tabEntityList.clear()
                tabEntityList.addAll(it)
                initViewPager()
                initTabLayout()
            } else {
                binding.reuseNoConnection.root.visibility = View.VISIBLE
            }
        }
    }

    private fun initViewPager() {
        adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = tabEntityList.size

            override fun createFragment(position: Int): Fragment {
                val tabEntity = tabEntityList.getOrNull(position)
                val subjectData = SubjectData(tabEntity?.id ?: "", tabEntity?.name ?: "", false)
                return HotGameListFragment().with(
                    bundleOf(
                        EntranceConsts.KEY_SUBJECT_DATA to subjectData,
                    )
                )
            }

        }
        binding.viewPager.adapter = adapter
        binding.viewPager.offscreenPageLimit = 3
    }

    private fun initTabLayout() {
        val tabLayout = binding.tabLayout
        val viewPager = binding.viewPager
        tabLayout.run {
            TabLayoutMediator(this, viewPager) { tab, position ->
                val tabEntity = tabEntityList.safelyGetInRelease(position)
                val view = LayoutInflater.from(context).inflate(R.layout.game_collection_hot_list_tab_item, null)
                view.findViewById<TextView>(R.id.tab_title)?.text = tabEntity?.name
                tab.customView = view
                updateTabStyle(tab, position == viewPager.currentItem)
            }.attach()
            val firstTabView = (getChildAt(0) as ViewGroup).getChildAt(0)
            firstTabView.layoutParams = (firstTabView.layoutParams as LinearLayout.LayoutParams).also {
                it.leftMargin = 16F.dip2px()
            }
            val lastTabView = (getChildAt(0) as ViewGroup).getChildAt(tabEntityList.size - 1)
            lastTabView.layoutParams = (lastTabView.layoutParams as LinearLayout.LayoutParams).also {
                it.rightMargin = 8F.dip2px()
            }
            addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    updateTabStyle(tab, true)
                }

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

                override fun onTabReselected(tab: TabLayout.Tab) {
                    updateTabStyle(tab, true)
                }
            })
        }
    }

    private fun updateTabStyle(tab: TabLayout.Tab, isChecked: Boolean) {
        tab.customView?.background =
            if (isChecked) R.drawable.bg_game_collection_hot_list_tab_selected.toDrawable(requireContext()) else R.drawable.bg_game_collection_hot_list_tab_unselected.toDrawable(
                requireContext()
            )
        tab.customView?.findViewById<TextView>(R.id.tab_title)?.run {
            setTextColor(
                if (isChecked) com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()) else com.gh.gamecenter.common.R.color.text_tertiary.toColor(
                    requireContext()
                )
            )
        }
    }

}