package com.gh.gamecenter.mygame

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.viewModels
import androidx.constraintlayout.widget.Group
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.gh.common.pop.BatchManagementPop
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.base.activity.BaseActivity_TabLayout.PAGE_INDEX
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.gamecenter.common.base.fragment.BaseFragment_TabLayout
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.BugFixedPopupWindow
import com.gh.gamecenter.common.view.TabIndicatorView
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.PopupMyGameGuideBinding
import com.gh.gamecenter.gamecollection.publish.GameCollectionEditActivity
import com.google.android.material.tabs.TabLayout
import com.therouter.router.Route

@Route(
    path = RouteConsts.activity.myGameActivity,
    description = "我的游戏"
)
class MyGameActivity : BaseActivity() {

    private val viewModel by viewModels<MyGameActivityViewModel>()

    private var checkedIndex = 0

    private val titles by lazy {
        listOf(R.string.played.toResString(), R.string.follow.toResString(), R.string.reserve.toResString())
    }

    private val batchManagePop by lazy {
        BatchManagementPop.create(
            this,
            object : BatchManagementPop.OnBatchManagementListener {

                override fun enableAutoDownload() {
                    viewModel.changePageStatus(MyReservationFragment.ReservePageState.EnableAutoDownload)
                }

                override fun batchManage() {
                    viewModel.changePageStatus(MyReservationFragment.ReservePageState.CancelReserve)

                }
            })
    }

    private lateinit var vBack: View
    private lateinit var vGameCollection: View
    private lateinit var gGameCollection: Group
    private lateinit var vMore: View
    private lateinit var tvCancel: TextView
    private lateinit var gMore: Group
    private lateinit var viewPager: ViewPager

    override fun getLayoutId(): Int = R.layout.activity_my_game

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)

        checkedIndex = intent.getIntExtra(PAGE_INDEX, 0)
        vBack = findViewById(R.id.v_back)
        vGameCollection = findViewById(R.id.v_game_collection)
        gGameCollection = findViewById(R.id.g_game_collection)
        vMore = findViewById(R.id.v_more)
        tvCancel = findViewById(R.id.tv_cancel)
        gMore = findViewById(R.id.g_more)
        viewPager = findViewById(R.id.activity_view_pager)

        vBack.setOnClickListener { finish() }
        vGameCollection.setOnClickListener {
            showRegulationTestDialogIfNeeded {
                startActivity(GameCollectionEditActivity.getCreateIntent(this, mEntrance, "我的游戏"))
            }
        }
        vMore.setOnClickListener {
            showBatchManagementPop()
        }

        tvCancel.setOnClickListener {
            viewModel.changePageStatus(MyReservationFragment.ReservePageState.Normal)
        }

        initFragmentList()

        with(viewModel) {
            reservePageStatus.observe(this@MyGameActivity, Observer {
                val tabPosition = viewPager.currentItem
                if (tabPosition == RESERVATION_INDEX) {
                    if (it is MyReservationFragment.ReservePageState.Normal) {
                        setViewsVisible(true, gGameCollection, gMore)
                        setViewsVisible(false, tvCancel)
                    } else {
                        setViewsVisible(false, gGameCollection, gMore)
                        setViewsVisible(true, tvCancel)
                    }
                } else {
                    setViewsVisible(true, gGameCollection)
                    setViewsVisible(false, gMore, tvCancel)
                }
            })
        }
    }

    private fun setViewsVisible(isVisible: Boolean, vararg views: View) {
        views.forEach {
            it.goneIf(!isVisible)
        }
    }


    fun initFragmentList() {
        val tabLayout = findViewById<TabLayout>(R.id.activity_tab_layout)
        val tabIndicatorView = findViewById<TabIndicatorView>(R.id.activity_tab_indicator)

        val fragments = listOf(MyPlayedGameFragment(), MyFollowedGameFragment(), MyReservationFragment())
        val pageAdapter = FragmentAdapter(supportFragmentManager, fragments, titles)
        viewPager.offscreenPageLimit = fragments.size
        viewPager.adapter = pageAdapter
        viewPager.setCurrentItem(checkedIndex)

        tabLayout.setupWithViewPager(viewPager)

        tabIndicatorView.setupWithTabLayout(tabLayout)
        tabIndicatorView.setupWithViewPager(viewPager)
        tabIndicatorView.setIndicatorWidth(20)

        for (i in 0 until tabLayout.tabCount) {
            val tab: TabLayout.Tab = tabLayout.getTabAt(i) ?: continue
            val tabTitle = if (tab.text != null) tab.text.toString() else ""
            val tabView = BaseFragment_TabLayout.createDefaultTabCustomView(this, tabTitle)
            tab.setCustomView(tabView)
        }
        BaseFragment_TabLayout.initTabStyle(tabLayout, checkedIndex)

        viewPager.addOnPageChangeListener(::onPageSelected)

        onPageSelected(checkedIndex)

        showGuide(checkedIndex)
    }

    fun onPageSelected(position: Int) {
        MtaHelper.onEvent("我的光环", "我的游戏", "${titles[position]}Tab")
        MtaHelper.onEvent("我的光环_新", "我的游戏", "${titles[position]}Tab")
        NewFlatLogUtils.logMyGameTabClick(titles[position])

        if (position == RESERVATION_INDEX) {
            gMore.goneIf(false)
        } else {
            gMore.goneIf(true)
        }
        // 用户切换了tab:退出编辑模式
        viewModel.changePageStatus(MyReservationFragment.ReservePageState.Normal)
    }

    private fun showBatchManagementPop() {
        if (!batchManagePop.isShowing) {
            batchManagePop.showAsDropDown(vMore, 0, (-4F).dip2px())
        }

    }

    override fun isAutoResetViewBackgroundEnabled() = true

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        updateStatusBarColor(com.gh.gamecenter.common.R.color.ui_surface, com.gh.gamecenter.common.R.color.ui_surface)
    }

    private fun showGuide(position: Int) {
        AppExecutor.uiExecutor.executeWithDelay({
            tryCatchInRelease {
                if (!SPUtils.getBoolean(Constants.SP_MY_GAME_GUIDE)) {
                    val binding = PopupMyGameGuideBinding.inflate(layoutInflater, null, false)
                    val popupWindow = BugFixedPopupWindow(
                        binding.root,
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT
                    )
                    binding.root.setOnClickListener {
                        SPUtils.setBoolean(Constants.SP_MY_GAME_GUIDE, true)
                        popupWindow.dismiss()
                    }

                    val paddingEnd = if (position == RESERVATION_INDEX) {
                        48F.dip2px()
                    } else {
                        0
                    }
                    binding.guideContainer.setPadding(0, 0, paddingEnd, 0)
                    popupWindow.run {
                        isTouchable = true
                        isFocusable = true
                        if (!isFinishing) {
                            showAtLocation(vGameCollection, Gravity.TOP, 0, 0)
                        }
                    }
                }
            }
        }, 500)
    }

    override fun handleBackPressed(): Boolean {
        if (viewModel.reservePageStatus.value == MyReservationFragment.ReservePageState.Normal) {
            return super.handleBackPressed()
        } else {
            viewModel.changePageStatus(MyReservationFragment.ReservePageState.Normal)
            return true
        }
    }

    companion object {
        const val PLAYED_INDEX = 0
        const val FOLLOWED_INDEX = 1
        const val RESERVATION_INDEX = 2

        @JvmStatic
        fun getIntentWithConfig(context: Context, defaultFragmentPosition: Int): Intent {
            val intent = Intent(context, MyGameActivity::class.java)
            intent.putExtra(PAGE_INDEX, defaultFragmentPosition)
            return intent
        }
    }

}