package com.gh.gamecenter.servers.gametest2

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
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.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.databinding.FragmentGameServerTestV2Binding
import com.gh.gamecenter.databinding.PopupFilterGameTypeBinding

class GameServerTestV2Fragment : LazyFragment() {

    private var mBinding: FragmentGameServerTestV2Binding? = null
    private var mViewModel: GameServerTestV2ViewModel? = null
    private var mPopupWindow: PopupWindow? = null
    private var mCurrentFragment: GameServerTestV2ListFragment? = null

    override fun getRealLayoutId(): Int = R.layout.fragment_game_server_test_v2

    override fun onRealLayoutInflated(inflatedView: View) {
        super.onRealLayoutInflated(inflatedView)
        mBinding = FragmentGameServerTestV2Binding.bind(inflatedView)
    }

    override fun onFragmentFirstVisible() {
        mViewModel = viewModelProviderFromParent()
        super.onFragmentFirstVisible()
        mViewModel?.selectedTimeFilterLiveData?.observe(this) {
            mBinding?.filterView?.updateSelectedFilter(it)
        }
        changeFragment()
    }

    override fun initRealView() {
        super.initRealView()
        mBinding?.filterView?.setupFilter(mViewModel?.timeFilterList!!, mViewModel?.selectedTimeFilterLiveData?.value) {
            mViewModel?.setSelectedTimeFilter(it)
            mCurrentFragment?.changeTimeFilter()
        }
        mBinding?.categoryContainer?.setOnClickListener {
            showSelectionPopupWindow {
                mViewModel?.selectedCategoryFilter = it
                mBinding?.categoryTv?.text = it
                val drawable = VectorDrawableCompat.create(resources, R.drawable.ic_filter_arrow, null)
                if (it != mViewModel?.categoryFilterList?.get(0)) {
                    mBinding?.categoryTv?.setTextColor(R.color.theme_font.toColor(requireContext()))
                    drawable?.setTint(R.color.theme_font.toColor(requireContext()))
                } else {
                    mBinding?.categoryTv?.setTextColor(R.color.text_subtitleDesc.toColor(requireContext()))
                    drawable?.setTint(R.color.text_subtitleDesc.toColor(requireContext()))
                }
                mBinding?.arrowIv?.setImageDrawable(drawable)
                mViewModel?.setSelectedTimeFilter(GameServerTestV2ViewModel.TODAY_GAME)
                mCurrentFragment?.changeCategoryFilter()
            }
        }
        mBinding?.filterGroup?.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.recommendRb -> {
                    mViewModel?.tabFilter = GameServerTestV2ViewModel.TestFilter.RECOMMEND
                    NewFlatLogUtils.logGameTestDetailTabClick("推荐")
                    changeFragment()
                }
                R.id.allRb -> {
                    mViewModel?.tabFilter = GameServerTestV2ViewModel.TestFilter.ALL
                    NewFlatLogUtils.logGameTestDetailTabClick("全部")
                    changeFragment()
                }
                else -> {
                    //Do nothing
                }
            }
        }
    }

    private fun showSelectionPopupWindow(selectedCallback: ((String) -> Unit)?) {
        val binding = PopupFilterGameTypeBinding.inflate(LayoutInflater.from(requireContext()), null, false)
        val popupWindow = PopupWindow(
            binding.root,
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        ).apply { mPopupWindow = this }


        for (filter in mViewModel?.categoryFilterList!!) {
            val itemWidth = (DisplayUtils.getScreenWidth() - 104F.dip2px()) / 4
            val item = getItemTextView(filter, itemWidth)
            binding.flexbox.addView(item)
            item.tag = filter
            toggleHighlightedTextView(item, mViewModel?.selectedCategoryFilter == filter)
            item.setOnClickListener {
                toggleHighlightedTextView(item, true)
                selectedCallback?.invoke(filter)
                popupWindow.dismiss()
            }
        }

        val originalColor = mBinding?.categoryTv?.textColors
        var drawable = VectorDrawableCompat.create(resources, R.drawable.ic_filter_arrow, null)
        drawable?.setTint(R.color.theme_font.toColor(requireContext()))
        mBinding?.arrowIv?.rotation = 0F
        mBinding?.arrowIv?.setImageDrawable(drawable)
        mBinding?.categoryTv?.setTextColor(R.color.theme_font.toColor(requireContext()))

        popupWindow.setOnDismissListener {
            drawable = VectorDrawableCompat.create(resources, R.drawable.ic_filter_arrow, null)
            drawable?.setTint(originalColor?.defaultColor ?: 0)
            mBinding?.arrowIv?.rotation = 180F
            mBinding?.arrowIv?.setImageDrawable(drawable)
            mBinding?.categoryTv?.setTextColor(originalColor)
        }
        binding.background.setOnClickListener {
            popupWindow.dismiss()
            mPopupWindow = null
        }

        popupWindow.isTouchable = true
        popupWindow.isFocusable = true
        popupWindow.animationStyle = 0
        popupWindow.showAsDropDown(mBinding?.filterContainer, 0, 0)
    }

    private fun getItemTextView(type: String, width: Int): TextView {
        return TextView(requireContext()).apply {
            text = type
            includeFontPadding = false
            textSize = 12F
            gravity = Gravity.CENTER
            setTypeface(Typeface.DEFAULT, Typeface.BOLD)
            setTextColor(R.color.white.toColor(context))
            val params = LinearLayout.LayoutParams(width, 24F.dip2px())
            layoutParams = params
        }
    }

    private fun toggleHighlightedTextView(targetTextView: TextView, highlightIt: Boolean) {
        if (highlightIt) {
            targetTextView.background = ContextCompat.getDrawable(targetTextView.context, R.drawable.bg_tag_text)
            targetTextView.setTextColor(Color.WHITE)
        } else {
            targetTextView.background = null
            targetTextView.setTextColor(ContextCompat.getColor(targetTextView.context, R.color.text_757575))
        }
    }

    private fun changeFragment() {
        mViewModel?.selectedTimeFilterLiveData?.value = mViewModel?.timeFilterList?.get(1) ?: ""
        mBinding?.filterView?.updateSelectedFilter(mViewModel?.selectedTimeFilterLiveData?.value ?: "")
        mCurrentFragment = if (mViewModel?.tabFilter == GameServerTestV2ViewModel.TestFilter.RECOMMEND) {
            childFragmentManager.findFragmentByTag(GameServerTestV2ViewModel.TestFilter.RECOMMEND.value) as? GameServerTestV2ListFragment
                ?: GameServerTestV2ListFragment()
        } else {
            childFragmentManager.findFragmentByTag(GameServerTestV2ViewModel.TestFilter.ALL.value) as? GameServerTestV2ListFragment
                ?: GameServerTestV2ListFragment()
        }
        val bundle = requireArguments().clone() as Bundle
        bundle.putString(EntranceConsts.KEY_FILTER, mViewModel?.tabFilter?.value)
        mCurrentFragment?.arguments = bundle
        childFragmentManager
            .beginTransaction()
            .replace(R.id.contentContainer, mCurrentFragment!!, mViewModel?.tabFilter?.value)
            .commitAllowingStateLoss()
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding?.filterView?.updateFilterRecyclerView()
        mBinding?.recommendRb?.setTextColor(
            ContextCompat.getColorStateList(
                requireContext(),
                R.color.game_server_test_rg_button_selector
            )
        )
        mBinding?.recommendRb?.background = R.drawable.game_server_test_rg_button_selector.toDrawable(requireContext())
        mBinding?.allRb?.setTextColor(
            ContextCompat.getColorStateList(
                requireContext(),
                R.color.game_server_test_rg_button_selector
            )
        )
        mBinding?.allRb?.background = R.drawable.game_server_test_rg_button_selector.toDrawable(requireContext())
    }
}