package com.gh.gamecenter.gamecollection.hotlist

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.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.FragmentGameCollectionHotListWrapperAlBinding
import com.gh.gamecenter.databinding.FragmentGameCollectionHotListWrapperBinding
import com.gh.gamecenter.entity.GameCollectionListEntity
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import kotlin.math.abs

class GameCollectionHotListWrapperFragment : LazyFragment() {

    private lateinit var mBinding: FragmentGameCollectionHotListWrapperBinding
    private lateinit var mAlternativeBinding: FragmentGameCollectionHotListWrapperAlBinding
    private lateinit var mViewModel: GameCollectionHotListWrapperViewModel

    private val mTabEntityList = arrayListOf<GameCollectionListEntity>()

    private var mAdapter: FragmentStateAdapter? = null

    private var mUseAlternativeLayout = false
    private var mIsCollapsed = false

    override fun getRealLayoutId(): Int = if (mUseAlternativeLayout) R.layout.fragment_game_collection_hot_list_wrapper_al else R.layout.fragment_game_collection_hot_list_wrapper

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mUseAlternativeLayout = mIsFromTabWrapper
    }

    override fun onFragmentPause() {
        super.onFragmentPause()
        val stayTime = (System.currentTimeMillis() - startPageTime) / 1000
        if (mTabEntityList.isNotEmpty() && stayTime >= 3) {
            val viewPager = if (mUseAlternativeLayout) mAlternativeBinding.viewPager else mBinding.viewPager
            NewFlatLogUtils.logGameCollectionHotListExit(
                stayTime,
                mTabEntityList.safelyGetInRelease(viewPager.currentItem)?.name ?: ""
            )
            SensorsBridge.trackEvent("ViewGameCollectHotRank", "stay_length", stayTime.toString())
        }
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        updateStatusBar()
    }

    private fun updateStatusBar() {
        if (!mIsFromTabWrapper && isSupportVisible) {
            DisplayUtils.transparentStatusBar(requireActivity())
            DisplayUtils.setLightStatusBar(requireActivity(), !mIsDarkModeOn && mIsCollapsed)
        }
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()
        mViewModel = viewModelProvider()

        mViewModel.hotListTabListLiveData.observe(this) {
            if (it != null) {
                mTabEntityList.clear()
                mTabEntityList.add(GameCollectionListEntity(name = PLAYER_CREATION_TAB_NAME, position = 0))
                mTabEntityList.addAll(it)

                initViewPager()
                initTabLayout()
            } else {
                if (mUseAlternativeLayout) {
                    mAlternativeBinding.reuseNoConnection.root.visibility = View.VISIBLE
                } else {
                    mBinding.reuseNoConnection.root.visibility = View.VISIBLE
                }
            }
        }

        NewFlatLogUtils.logGameCollectionHotListEnter(mEntrance)
        SensorsBridge.trackEvent("GameCollectHotRankEnter")
    }

    override fun onRealLayoutInflated(inflatedView: View) {
        super.onRealLayoutInflated(inflatedView)
        if (mUseAlternativeLayout) {
            mAlternativeBinding = FragmentGameCollectionHotListWrapperAlBinding.bind(inflatedView)
        } else {
            mBinding = FragmentGameCollectionHotListWrapperBinding.bind(inflatedView)
        }
    }

    override fun initRealView() {
        super.initRealView()
        if (mUseAlternativeLayout) {
            mAlternativeBinding.run {
                tabContainer.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
                reuseNoConnection.connectionReloadTv.setOnClickListener {
                    reuseNoConnection.root.visibility = View.GONE
                    mViewModel.getGameCollectionHotListTab()
                }
            }
        } else {
            updateStatusBar()
            changeToolbarStyle(mIsCollapsed)
            mBinding.run {
                val statusBarHeight = DisplayUtils.getStatusBarHeight(requireContext().resources)
                if (!mIsFromTabWrapper) {
                    ViewCompat.setOnApplyWindowInsetsListener(appbar) { _, insets ->
                        (toolbar.layoutParams as ViewGroup.MarginLayoutParams).topMargin =
                            insets.getInsets(WindowInsetsCompat.Type.systemBars()).top
                        WindowInsetsCompat.CONSUMED
                    }
                }
                if (mIsFromMainWrapper) {
                    (toolbar.layoutParams as ViewGroup.MarginLayoutParams).topMargin = statusBarHeight
                }
                val collapsingTrigger = 66F.dip2px() + statusBarHeight

                if (mIsFromMainWrapper) {
                    toolbar.navigationIcon = null
                } else {
                    toolbar.setNavigationIcon(com.gh.gamecenter.common.R.drawable.ic_bar_back_light)
                }
                toolbar.setNavigationOnClickListener { requireActivity().finish() }

                collapsingToolbar.scrimVisibleHeightTrigger = collapsingTrigger
                collapsingToolbar.scrimShownAction = {
                    if (mIsCollapsed != it) {
                        mIsCollapsed = it
                        updateStatusBar()
                        changeToolbarStyle(it)
                    }
                }

                appbar.addOnOffsetChangedListener { _, verticalOffset ->
                    val absOffset = abs(verticalOffset)
                    val currentFragment = childFragmentManager.findFragmentByTag("f${mBinding.viewPager.currentItem}")
                    if (currentFragment is GameCollectionPlayerCreationFragment) {
                        currentFragment.setListRefreshEnable(absOffset <= 2)
                    } else if (currentFragment is GameCollectionHotListFragment) {
                        currentFragment.setListRefreshEnable(absOffset <= 2)
                    }
                }

                reuseNoConnection.connectionReloadTv.setOnClickListener {
                    reuseNoConnection.root.visibility = View.GONE
                    mViewModel.getGameCollectionHotListTab()
                }
            }
        }
    }

    private fun changeToolbarStyle(isCollapsed: Boolean) {
        if (isCollapsed) {
            if (!mIsFromMainWrapper) {
                mBinding.toolbar.setNavigationIcon(com.gh.gamecenter.common.R.drawable.ic_bar_back)
            }
            mBinding.titleTv.alpha = 1F
            mBinding.titleTv.visibility = View.VISIBLE
            mBinding.titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_black.toColor(requireContext()))
            mBinding.collapsingToolbar.setContentScrimColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
            mBinding.tabContainer.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(requireContext()))
        } else {
            if (!mIsFromMainWrapper) {
                mBinding.toolbar.setNavigationIcon(com.gh.gamecenter.common.R.drawable.ic_bar_back_light)
            }
            mBinding.titleTv.visibility = View.GONE
            mBinding.collapsingToolbar.setContentScrimColor(com.gh.gamecenter.common.R.color.ui_background.toColor(requireContext()))
            mBinding.tabContainer.background = null
        }
    }

    private fun initTabLayout() {
        val tabLayout = if (mUseAlternativeLayout) mAlternativeBinding.tabLayout else mBinding.tabLayout
        val viewPager = if (mUseAlternativeLayout) mAlternativeBinding.viewPager else mBinding.viewPager
        tabLayout.run {
            TabLayoutMediator(this, viewPager) { tab, position ->
                val tabEntity = mTabEntityList.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(mTabEntityList.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)

                    val tabEntity = mTabEntityList.safelyGetInRelease(tab.position)
                    NewFlatLogUtils.logGameCollectionHotListTabClick(
                        tabEntity?.name ?: "",
                        tabEntity?.id ?: "",
                        tabEntity?.name ?: ""
                    )
                    SensorsBridge.trackEvent("GameCollectHotRankTabSelect", json {
                        "position" to tab.position
                        "tab_content" to tabEntity?.name
                        "game_list_collection_name" to tabEntity?.name
                        "game_list_collection_id" to tabEntity?.id
                    })
                }

                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()
                )
            )
        }
    }

    private fun initViewPager() {
        val exposureSourceList = arguments?.getParcelableArrayList(EntranceConsts.KEY_EXPOSURE_SOURCE_LIST) ?: arrayListOf<ExposureSource>()
        mAdapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = mTabEntityList.size

            override fun createFragment(position: Int): Fragment {
                val tabEntity = mTabEntityList.safelyGetInRelease(position)
                return if (position == 0) {
                    GameCollectionPlayerCreationFragment().with(
                        bundleOf(
                            EntranceConsts.KEY_ENTRANCE to mEntrance,
                            EntranceConsts.KEY_PATH to "游戏单热榜",
                            EntranceConsts.KEY_EXPOSURE_SOURCE_LIST to ArrayList(exposureSourceList)
                        )
                    )
                } else {
                    GameCollectionHotListFragment().with(
                        bundleOf(
                            GameCollectionListEntity::class.java.simpleName to tabEntity,
                            EntranceConsts.KEY_POSITION to position,
                            EntranceConsts.KEY_ENTRANCE to mEntrance,
                            EntranceConsts.KEY_PATH to "游戏单热榜",
                            EntranceConsts.KEY_EXPOSURE_SOURCE_LIST to ArrayList(exposureSourceList)
                        )
                    )
                }
            }

        }
        if (mUseAlternativeLayout) {
            mAlternativeBinding.viewPager.adapter = mAdapter
            mAlternativeBinding.viewPager.isUserInputEnabled = false
            mAlternativeBinding.viewPager.offscreenPageLimit = 3
        } else {
            mBinding.viewPager.adapter = mAdapter
            mBinding.viewPager.isUserInputEnabled = false
            mBinding.viewPager.offscreenPageLimit = 3
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (!::mBinding.isInitialized && !::mAlternativeBinding.isInitialized) {
            return
        }
        if (!mUseAlternativeLayout) {
            updateStatusBar()
            changeToolbarStyle(mIsCollapsed)
        }

        val tabCount =
            if (mUseAlternativeLayout) mAlternativeBinding.tabLayout.tabCount else mBinding.tabLayout.tabCount
        for (i in 0 until tabCount) {
            val tab =
                if (mUseAlternativeLayout) mAlternativeBinding.tabLayout.getTabAt(i) else mBinding.tabLayout.getTabAt(i)
            if (tab != null) {
                updateTabStyle(tab, tab.isSelected)
            }
        }
    }

    companion object {
        const val PLAYER_CREATION_TAB_NAME = "#玩家创作榜"
    }
}