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.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.common.utils.toDrawable
import com.gh.gamecenter.databinding.ItemFilterBinding
import com.gh.gamecenter.databinding.LayoutFilterBinding
import com.google.android.flexbox.FlexboxLayout

// TODO 把 ConfigFilterView 的上层实现切换到继承这个类实现
class FilterView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    ConstraintLayout(context, attrs, defStyleAttr) {

    private var mBinding: LayoutFilterBinding? = null

    private var mMainFilterList: ArrayList<String> = arrayListOf()
    private var mSubFilterList: ArrayList<String> = arrayListOf()

    private var mSelectedMainFilter: String = ""
    private var mSelectedSubFilter: String = ""

    private var mHighlightSubFilterIfItsNotDefault: Boolean = false // 当次 filter 选中非默认的时候高亮显示

    private var mPopupWindow: PopupWindow? = null
    private var mSubFilterSelectedCallback: ((String) -> Unit)? = null

    init {
        mBinding = LayoutFilterBinding.inflate(LayoutInflater.from(context), this, true)
    }

    fun setupFilter(
        mainFilterList: ArrayList<String>,
        defaultSelectedMainFilter: String? = null,
        subFilterList: ArrayList<String>,
        subFilterText: String,
        mainFilterSelectedCallback: ((String) -> Unit),
        subFilterSelectedCallback: ((String) -> Unit),
        highlightSubFilterIfNotDefault: Boolean = false
    ) {
        mMainFilterList = mainFilterList
        mSubFilterList = subFilterList
        mSubFilterSelectedCallback = subFilterSelectedCallback

        mHighlightSubFilterIfItsNotDefault = highlightSubFilterIfNotDefault

        mBinding?.subFilterTv?.text = subFilterText
        mBinding?.subFilterTv?.setOnClickListener {
            showSelectionPopupWindow(this, it as TextView, mSelectedSubFilter) { selectedText ->
                mSubFilterSelectedCallback?.invoke(selectedText)
            }
        }

        mBinding?.filterRecyclerView?.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        mBinding?.filterRecyclerView?.adapter = FilterAdapter(
            context,
            mMainFilterList,
            defaultSelectedMainFilter ?: mainFilterList.first()
        ) {
            mainFilterSelectedCallback.invoke(it)
        }
    }

    fun updateSelectedMainFilter(filter: String) {
        mSelectedMainFilter = filter
        (mBinding?.filterRecyclerView?.adapter as? FilterAdapter)?.updateSelectedFilter(filter)
        mBinding?.filterRecyclerView?.smoothScrollToPosition(mMainFilterList.indexOf(filter))
    }

    fun updateSelectedSubFilter(filter: String) {
        mSelectedSubFilter = filter
        mBinding?.subFilterTv?.text = filter
        if (filter != mSubFilterList.firstOrNull() && mHighlightSubFilterIfItsNotDefault) {
            mBinding?.subFilterTv?.setTextColor(R.color.theme_font.toColor(context))
        } else {
            mBinding?.subFilterTv?.setTextColor(R.color.text_757575.toColor(context))
        }
    }

    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 showSelectionPopupWindow(
        containerView: View,
        subFilterTv: TextView,
        subFilterText: String,
        selectedCallback: ((String) -> Unit)
    ) {
        subFilterTv.setTextColor(R.color.theme_font.toColor(context))
        subFilterTv.setDrawableEnd(R.drawable.ic_filter_arrow_up)

        val inflater = LayoutInflater.from(subFilterTv.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)

        flexboxLayout.setPadding(16F.dip2px(), 0, 0, 8F.dip2px())

        backgroundView.setOnClickListener {
            popupWindow.dismiss()
            mPopupWindow = null
        }

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

            val height = item.layoutParams.height

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

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

            if (subFilterText == filter) {
                toggleHighlightedTextView(tv, true)
            } else {
                toggleHighlightedTextView(tv, false)
            }

            tv.tag = filter

            item.setOnClickListener {
                toggleHighlightedTextView(tv, true)
                popupWindow.dismiss()
                subFilterTv.text = filter

                updateSelectedSubFilter(filter)
                selectedCallback.invoke(filter)
            }
        }

        popupWindow.setOnDismissListener {
            subFilterTv.setDrawableEnd(R.drawable.ic_filter_arrow_down)
        }

        popupWindow.isTouchable = true
        popupWindow.isFocusable = true
        popupWindow.animationStyle = 0
        // 在模拟器上会有 1dp 的位移
        popupWindow.showAsDropDown(containerView, 0, -6)
    }

    fun setRootBackgroundColor(@ColorInt color: Int) {
        mBinding?.root?.setBackgroundColor(color)
    }

    fun updateFilterRecyclerView() {
        mBinding?.filterRecyclerView?.adapter?.run {
            mBinding?.filterRecyclerView?.recycledViewPool?.clear()
            notifyItemRangeChanged(0, itemCount)
        }
    }

    fun updatePopupWindow() {
        mBinding?.run {
            if (mPopupWindow != null && mPopupWindow!!.isShowing) {
                mPopupWindow?.dismiss()
                showSelectionPopupWindow(this@FilterView, subFilterTv, subFilterTv.text.toString()) { selectedText ->
                    mSubFilterSelectedCallback?.invoke(selectedText)
                }
            }
        }
    }

    class FilterAdapter(
        val context: Context,
        private val mFilterList: ArrayList<String>,
        private val mDefaultSelectedFilter: String,
        private val mClickCallback: (String) -> Unit
    ) : RecyclerView.Adapter<FilterAdapter.FilterViewHolder>() {

        private var mSelectedFilter = mDefaultSelectedFilter

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FilterViewHolder {
            return FilterViewHolder(ItemFilterBinding.inflate(LayoutInflater.from(context)))
        }

        override fun getItemCount() = mFilterList.size

        override fun onBindViewHolder(holder: FilterViewHolder, position: Int) {
            if (mSelectedFilter == "") {
                mSelectedFilter = mFilterList.first()
            }

            if (mSelectedFilter == mFilterList[position]) {
                holder.binding.titleTv.background = R.drawable.bg_tag_text.toDrawable(context)
                holder.binding.titleTv.setTextColor(R.color.white.toColor(context))
            } else {
                holder.binding.titleTv.setBackgroundColor(R.color.background_white.toColor(context))
                holder.binding.titleTv.setTextColor(R.color.text_777777.toColor(context))
            }

            holder.binding.titleTv.text = mFilterList[position]

            holder.binding.root.setOnClickListener {
                mClickCallback.invoke(mFilterList[position])
                updateSelectedFilter(mFilterList[position])
            }
        }

        fun updateSelectedFilter(incomingSelectedFilter: String) {
            if (mSelectedFilter != incomingSelectedFilter) {
                mSelectedFilter = incomingSelectedFilter
                notifyDataSetChanged()
            }
        }

        class FilterViewHolder(var binding: ItemFilterBinding) : RecyclerView.ViewHolder(binding.root)
    }

}