package com.gh.common.view

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.dip2px
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

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

    private var mTypeTv: TextView
    private var mCatalogTv: TextView
    private var mSizeTv: TextView
    private var mTypeContainer: View
    private var mCatalogContainer: View
    private var mSizeContainer: View

    private var mTypeFilterArray = arrayOf(SortType.RECOMMENDED, SortType.NEWEST, SortType.RATING)
    private var sizeFilterArray: ArrayList<SubjectSettingEntity.Size>? = null

    private var mOnCategoryFilterSetupListener: OnCategoryFilterSetupListener? = null
    private var mOnFilterClickListener: OnFilterClickListener? = null

    private var mTypePopupWindow: PopupWindow? = null
    private var mSizePopupWindow: PopupWindow? = null

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

        mTypeTv = findViewById(R.id.type_tv)
        mCatalogTv = findViewById(R.id.catalog_tv)
        mSizeTv = findViewById(R.id.size_tv)
        mTypeContainer = findViewById(R.id.container_type)
        mCatalogContainer = findViewById(R.id.container_category)
        mSizeContainer = findViewById(R.id.container_size)
        mTypeTv.text = mTypeFilterArray[0].value

        mTypeContainer.setOnClickListener {
            mOnFilterClickListener?.onTypeClick()
            showSelectTypePopupWindow(this, mTypeTv, mTypeTv.text.toString())
        }

        mCatalogContainer.setOnClickListener {
            mOnFilterClickListener?.onCategoryClick()
            mOnCategoryFilterSetupListener?.onSetupSortCategory()
        }

        mSizeContainer.setOnClickListener {
            mOnFilterClickListener?.onSizeClick()
            showSelectSizePopupWindow(this, mSizeTv, mSizeTv.text.toString())
        }
    }

    fun setOnConfigSetupListener(onCategoryFilterSetupListener: OnCategoryFilterSetupListener) {
        mOnCategoryFilterSetupListener = onCategoryFilterSetupListener
    }

    fun setOnFilterClickListener(onFilterClickListener: OnFilterClickListener) {
        mOnFilterClickListener = onFilterClickListener
    }

    fun resetSortSize() {
        mSizeTv.text = "全部大小"
    }

    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 showSelectTypePopupWindow(containerView: View, typeTv: TextView, typeText: String) {
        typeTv.setTextColor(R.color.theme_font.toColor(context))
        typeTv.setDrawableEnd(R.drawable.ic_filter_arrow_up)

        val inflater = LayoutInflater.from(typeTv.context)
        val layout = inflater.inflate(R.layout.layout_filter_size, null)
        val windowWidth = typeTv.context.resources.displayMetrics.widthPixels - 80F.dip2px()
        val popupWindow = PopupWindow(
            layout,
            windowWidth,
            LayoutParams.WRAP_CONTENT
        ).apply { mTypePopupWindow = this }

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

        backgroundView.setOnClickListener {
            popupWindow.dismiss()
        }

        for (type in mTypeFilterArray) {
            val item = inflater.inflate(R.layout.item_filter_size, flexboxLayout, false)

            // 单列 3 个，强行设置宽度为屏幕的 1/3
            val width = windowWidth / 3
            val height = item.layoutParams.height

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

            val tv = item.findViewById<TextView>(R.id.size_tv)
            tv.text = type.value

            toggleHighlightedTextView(tv, typeText == type.value)

            tv.tag = type.value

            item.setOnClickListener {
                toggleHighlightedTextView(tv, true)
                popupWindow.dismiss()
                typeTv.text = type.value

                mOnCategoryFilterSetupListener?.onSetupSortType(type)
            }
        }

        popupWindow.setOnDismissListener {
            typeTv.setTextColor(R.color.text_757575.toColor(context))
            typeTv.setDrawableEnd(R.drawable.ic_filter_arrow_down)
            mTypePopupWindow = null
        }

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

    private fun showSelectSizePopupWindow(containerView: View, sizeTv: TextView, sizeText: String) {
        sizeTv.setTextColor(R.color.theme_font.toColor(context))
        sizeTv.setDrawableEnd(R.drawable.ic_filter_arrow_up)

        val inflater = LayoutInflater.from(sizeTv.context)
        val layout = inflater.inflate(R.layout.layout_filter_size, null)
        val windowWidth = sizeTv.context.resources.displayMetrics.widthPixels - 80F.dip2px()
        val popupWindow = PopupWindow(
            layout,
            windowWidth,
            LayoutParams.WRAP_CONTENT
        ).apply { mSizePopupWindow = 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 = "全部大小"))
                }
            }
        }

        backgroundView.setOnClickListener {
            popupWindow.dismiss()
        }

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

            // 单列 3 个，强行设置宽度为屏幕的 1/3
            val width = windowWidth / 3
            val height = item.layoutParams.height

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

            val tv = item.findViewById<TextView>(R.id.size_tv)
            tv.text = size.text

            toggleHighlightedTextView(tv, sizeText == size.text)

            tv.tag = size.text

            item.setOnClickListener {
                toggleHighlightedTextView(tv, true)
                popupWindow.dismiss()
                sizeTv.text = size.text

                mOnCategoryFilterSetupListener?.onSetupSortSize(size)
            }
        }

        popupWindow.setOnDismissListener {
            sizeTv.setTextColor(R.color.text_757575.toColor(context))
            sizeTv.setDrawableEnd(R.drawable.ic_filter_arrow_down)
            mSizePopupWindow = 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 setRootBackgroundColor(@ColorInt color: Int) {
        findViewById<View>(R.id.config_controller).setBackgroundColor(color)
    }

    fun setItemTextColor(@ColorInt color: Int) {
        mTypeTv.setTextColor(color)
        mCatalogTv.setTextColor(color)
        mSizeTv.setTextColor(color)
    }

    fun updatePopupWindow() {
        when {
            mTypePopupWindow != null && mTypePopupWindow!!.isShowing -> {
                mTypePopupWindow?.dismiss()
                showSelectTypePopupWindow(this, mTypeTv, mTypeTv.text.toString())
            }

            mSizePopupWindow != null && mSizePopupWindow!!.isShowing -> {
                mSizePopupWindow?.dismiss()
                showSelectSizePopupWindow(this, mSizeTv, mSizeTv.text.toString())
            }
        }
    }

    interface OnCategoryFilterSetupListener {
        fun onSetupSortSize(sortSize: SubjectSettingEntity.Size)
        fun onSetupSortType(sortType: SortType)
        fun onSetupSortCategory()
    }

    interface OnFilterClickListener {
        fun onCategoryClick()
        fun onTypeClick()
        fun onSizeClick()
    }

    enum class SortType(val value: String) {
        RECOMMENDED("热门推荐"),
        NEWEST("最新上线"),
        RATING("最高评分")
    }
}