package com.gh.common.view

import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.forEach
import androidx.core.view.setPadding
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.setDrawableEnd
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.entity.SubjectSettingEntity
import com.google.android.flexbox.FlexboxLayout
import splitties.views.leftPadding

class ConfigFilterView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private var mSizeTv: TextView
    private var mPopupWindow: PopupWindow? = null

    var newestTv: TextView
    var ratingTv: TextView //目前只在专题页面显示
    var recommendedTv: TextView
    var updateTv: TextView //更新
    var container: View
    private var dot1: View
    private var dot2: View
    private var dot3: View

    private var sizeFilterArray: ArrayList<SubjectSettingEntity.Size>? = null

    private var mOnConfigFilterSetupListener: OnConfigFilterSetupListener? = null
    private var mSelectionTvList: ArrayList<TextView>
    private var highlightedSortedType: SortType? = null

    init {
        View.inflate(context, R.layout.layout_config_filter, this)

        mSizeTv = findViewById(R.id.size_tv)
        newestTv = findViewById(R.id.newest_tv)
        ratingTv = findViewById(R.id.rating_tv)
        updateTv = findViewById(R.id.updateTv)
        recommendedTv = findViewById(R.id.recommended_tv)
        container = findViewById(R.id.config_controller)
        dot1 = findViewById(R.id.dot1)
        dot2 = findViewById(R.id.dot2)
        dot3 = findViewById(R.id.dot3)

        mSelectionTvList = arrayListOf(newestTv, ratingTv, updateTv, recommendedTv)

        mSizeTv.setOnClickListener {
            mOnConfigFilterSetupListener?.onShowSortSize()
            showSelectionPopupWindow(this, mSizeTv, mSizeTv.text.toString())
        }

        ratingTv.setOnClickListener {
            highlightedSortedType = SortType.RATING
            mOnConfigFilterSetupListener?.onSetupSortType(SortType.RATING)
            updateHighlightedTextView(ratingTv)
        }

        updateTv.setOnClickListener {
            highlightedSortedType = SortType.UPDATE
            mOnConfigFilterSetupListener?.onSetupSortType(SortType.UPDATE)
            updateHighlightedTextView(updateTv)
        }

        newestTv.setOnClickListener {
            highlightedSortedType = SortType.NEWEST
            mOnConfigFilterSetupListener?.onSetupSortType(SortType.NEWEST)
            updateHighlightedTextView(newestTv)
        }

        recommendedTv.setOnClickListener {
            highlightedSortedType = SortType.RECOMMENDED
            mOnConfigFilterSetupListener?.onSetupSortType(SortType.RECOMMENDED)
            updateHighlightedTextView(recommendedTv)
        }

        updateAllTextView(SortType.UPDATE)
    }

    private fun updateHighlightedTextView(highlightedTv: TextView) {
        for (tv in mSelectionTvList) {
            toggleHighlightedTextView(tv, tv == highlightedTv)
        }
    }

    fun updateAllTextView(sortType: SortType? = highlightedSortedType) {
        highlightedSortedType = sortType
        sortType?.let {
            when (it) {
                SortType.RECOMMENDED -> updateHighlightedTextView(recommendedTv)
                SortType.NEWEST -> updateHighlightedTextView(newestTv)
                SortType.RATING -> updateHighlightedTextView(ratingTv)
                SortType.UPDATE -> updateHighlightedTextView(updateTv)
            }
            mSizeTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
        }
    }

    fun setOnConfigSetupListener(onConfigFilterSetupListener: OnConfigFilterSetupListener) {
        mOnConfigFilterSetupListener = onConfigFilterSetupListener
    }

    private fun toggleHighlightedTextView(targetTextView: TextView, highlightIt: Boolean) {
        if (highlightIt) {
            targetTextView.setTextColor(com.gh.gamecenter.common.R.color.text_secondary.toColor(context))
            targetTextView.setTypeface(Typeface.DEFAULT, Typeface.BOLD)
        } else {
            targetTextView.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
            targetTextView.setTypeface(Typeface.DEFAULT, Typeface.NORMAL)
        }
    }

    fun updatePopupWindow() {
        if (mPopupWindow != null) {
            mPopupWindow?.dismiss()
            showSelectionPopupWindow(this, mSizeTv, mSizeTv.text.toString())
        }
    }

    private fun showSelectionPopupWindow(containerView: View, sizeTv: TextView, sizeText: String) {
        sizeTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(sizeTv.context))
        sizeTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_up_primary_8)

        val inflater = LayoutInflater.from(sizeTv.context)
        val layout = inflater.inflate(R.layout.layout_filter_size, null)
        val popupWindow = PopupWindow(
            layout,
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        ).apply { mPopupWindow = this }

        val flexboxLayout = layout.findViewById<FlexboxLayout>(R.id.flexbox)
        val backgroundView = layout.findViewById<View>(R.id.background)

        sizeFilterArray = if (sizeFilterArray == null) {
            getDefaultSizeFilterArray()
        } else {
            sizeFilterArray?.apply {
                if (firstOrNull()?.text != "全部大小") {
                    add(0, SubjectSettingEntity.Size(min = -1, max = -1, text = "全部大小"))
                }
            }
        }

        flexboxLayout.setOnClickListener {  }
        backgroundView.setOnClickListener {
            popupWindow.dismiss()
        }

        for (size in sizeFilterArray!!) {
            val item = inflater.inflate(R.layout.item_config_filter_size, flexboxLayout, false)

            // 单列 4 个，强行设置宽度为屏幕的 1/4
            val width = (sizeTv.context.resources.displayMetrics.widthPixels - 56F.dip2px()) / 4
            val height = item.layoutParams.height

            item.layoutParams = ViewGroup.LayoutParams(width, height)
            flexboxLayout.addView(item)

            val tv = item.findViewById<CheckedTextView>(R.id.size_tv)
            tv.text = size.text
            tv.isChecked = sizeText == size.text
            tv.tag = size.text

            tv.setOnClickListener {
                flexboxLayout.forEach { checkedTv ->
                    (checkedTv as CheckedTextView).isChecked = checkedTv == tv
                }
                popupWindow.dismiss()
                sizeTv.text = size.text
                mOnConfigFilterSetupListener?.onSetupSortSize(size)
            }
        }

        popupWindow.setOnDismissListener {
            sizeTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(sizeTv.context))
            sizeTv.setDrawableEnd(R.drawable.ic_auxiliary_arrow_down_8)
            mPopupWindow = null
        }

        popupWindow.isTouchable = true
        popupWindow.isFocusable = true
        popupWindow.animationStyle = 0
        popupWindow.showAsDropDown(containerView, 0, 0)
    }

    private fun getDefaultSizeFilterArray(): ArrayList<SubjectSettingEntity.Size> {
        return arrayListOf<SubjectSettingEntity.Size>().apply {
            add(SubjectSettingEntity.Size(min = -1, max = -1, text = "全部大小"))
            add(SubjectSettingEntity.Size(min = -1, max = 100, text = "100M以下"))
            add(SubjectSettingEntity.Size(min = 100, max = 300, text = "100-300M"))
            add(SubjectSettingEntity.Size(min = 300, max = 500, text = "300-500M"))
            add(SubjectSettingEntity.Size(min = 500, max = 1000, text = "500M-1G"))
            add(SubjectSettingEntity.Size(min = 1000, max = -1, text = "1G以上"))
        }
    }

    fun initSubjectFilterView(subjectSetting: SubjectSettingEntity) {
        ratingTv.visibility = View.VISIBLE

        if (subjectSetting.typeEntity.layout == "hide") {
            container.leftPadding = 8F.dip2px()
        }

        if (subjectSetting.filterOptions.size > 1) {
            // 重排序
            subjectSetting.filterOptions.forEachIndexed { index, s ->
                when (index) {
                    0 -> updateTv.text = s
                    1 -> recommendedTv.text = s
                    2 -> newestTv.text = s
                    3 -> ratingTv.text = s
                }
            }
        } else {
            updateTv.setPadding(0)
            updateTv.setTypeface(Typeface.DEFAULT, Typeface.NORMAL)
            updateTv.isClickable = false
            updateTv.text = when (subjectSetting.filterOptions.first()) {
                "推荐" -> "根据光环推荐排序"
                "最新" -> "根据游戏上新排序"
                "评分" -> "根据游戏评分排序"
                "更新" -> "根据更新时间排序"
                else -> subjectSetting.filterOptions.first()
            }
        }

        // 隐藏相关选项
        updateTv.goneIf(subjectSetting.filterOptions.isEmpty())
        recommendedTv.goneIf(subjectSetting.filterOptions.size <= 1)
        dot1.goneIf(subjectSetting.filterOptions.size <= 1)
        newestTv.goneIf(subjectSetting.filterOptions.size <= 2)
        dot2.goneIf(subjectSetting.filterOptions.size <= 2)
        ratingTv.goneIf(subjectSetting.filterOptions.size <= 3)
        dot3.goneIf(subjectSetting.filterOptions.size <= 3)
        sizeFilterArray = subjectSetting.filterSizes

        if (subjectSetting.filterOptions.size == 1) {
            updateTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
            updateTv.setTypeface(Typeface.DEFAULT, Typeface.NORMAL)
            highlightedSortedType = null
        }
    }

    interface OnConfigFilterSetupListener {
        fun onShowSortSize()
        fun onSetupSortSize(sortSize: SubjectSettingEntity.Size)
        fun onSetupSortType(sortType: SortType)
    }

    enum class SortType {
        RECOMMENDED,
        NEWEST,
        RATING,
        UPDATE
    }

}