package com.gh.gamecenter.common.base.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.gamecenter.common.view.TabIndicatorView
import com.google.android.material.tabs.TabLayout
import com.lightgame.view.NoScrollableViewPager

abstract class BaseLazyTabFragment : BaseLazyFragment(), ViewPager.OnPageChangeListener {

    lateinit var mTabLayout: TabLayout
    lateinit var mViewPager: NoScrollableViewPager
    lateinit var mTabIndicatorView: TabIndicatorView

    var mFragmentsList: MutableList<Fragment> = arrayListOf()

    var mTabTitleList: MutableList<String> = arrayListOf()

    var mCheckedIndex = 0

    abstract fun initFragmentList(fragments: MutableList<Fragment>)

    abstract fun initTabTitleList(tabTitleList: MutableList<String>)

    protected open fun provideIndicatorWidth(): Int {
        return 20
    }

    protected open fun provideTabView(position: Int, tabTitle: String?): View? {
        return null
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_tablayout_viewpager
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val fragments = childFragmentManager.fragments
        if (fragments != null) {
            for (fragment in fragments) {
                fragment.onActivityResult(requestCode, resultCode, data)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (arguments != null) mCheckedIndex = requireArguments().getInt(PAGE_INDEX, 0)
    }

    open fun providePagerAdapter(): PagerAdapter? {
        return null
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mTabLayout = view.findViewById(R.id.fragment_tab_layout)
        mViewPager = view.findViewById(R.id.fragment_view_pager)
        mTabIndicatorView = view.findViewById(R.id.fragment_tab_indicator)
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        mTabTitleList.clear()
        mFragmentsList.clear()

        initTabTitleList(mTabTitleList)
        mFragmentsList.addAll(restoreFragments())
        if (mFragmentsList.isEmpty() || mFragmentsList.size != mTabTitleList.size) {
            mFragmentsList.clear()
            initFragmentList(mFragmentsList)
        }

        mViewPager.offscreenPageLimit = mFragmentsList.size
        mViewPager.addOnPageChangeListener(this)
        mViewPager.adapter = providePagerAdapter()
            ?: FragmentAdapter(childFragmentManager, mFragmentsList, mTabTitleList)
        mViewPager.currentItem = mCheckedIndex
        mTabLayout.setupWithViewPager(mViewPager)
        mTabIndicatorView.setupWithTabLayout(mTabLayout)
        mTabIndicatorView.setupWithViewPager(mViewPager)
        mTabIndicatorView.setIndicatorWidth(provideIndicatorWidth())
        for (i in 0 until mTabLayout.tabCount) {
            val tab = mTabLayout.getTabAt(i) ?: continue
            val tabTitle = if (tab.text != null) tab.text.toString() else ""
            var tabView = provideTabView(i, tabTitle)
            if (tabView == null) tabView = BaseFragment_TabLayout.createDefaultTabCustomView(requireContext(), tabTitle)
            tab.customView = tabView
        }
        BaseFragment_TabLayout.initTabStyle(mTabLayout, mCheckedIndex)
    }

    protected fun restoreFragments(): ArrayList<Fragment> {
        val tag = "android:switcher:${mViewPager.id}:"
        val fragments = ArrayList<Fragment>()
        val childCount = mTabTitleList.size
        for (index in 0 until childCount) {
            val fragment = childFragmentManager.findFragmentByTag("$tag$index")
            if (fragment != null) {
                restoreFragment(fragment)
                fragments.add(fragment)
            }
        }
        return fragments
    }

    open fun restoreFragment(fragment: Fragment) {}

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

    override fun onPageSelected(position: Int) {}

    override fun onPageScrollStateChanged(state: Int) {}

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        val container = requireView().findViewById<View>(R.id.fragment_tab_container)
        if (container != null) {
            container.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.background_white))
            for (i in 0 until mTabLayout.tabCount) {
                val tab = mTabLayout.getTabAt(i)
                if (tab != null) {
                    BaseFragment_TabLayout.updateTabStyle(tab, tab.isSelected)
                }
            }
        }
    }

    companion object {
        const val PAGE_INDEX = "PAGE_INDEX"
    }
}