package com.develop.food.base.widgets

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.RelativeLayout
import androidx.recyclerview.widget.RecyclerView
import com.develop.base.R
import com.develop.base.databinding.CommonSearchViewBinding
import com.develop.base.databinding.PopFilterViewBinding
import com.develop.food.base.adapter.CommonSearchAdapter
import com.develop.food.base.data.model.CommonSearchItem
import com.develop.food.base.data.model.CommonSearchModel
import com.develop.food.base.utils.ResDimension
import com.google.android.flexbox.*

class CommonSearchLayout : LinearLayout {

    private var binding: CommonSearchViewBinding

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }

    private var commonSearchAdapter = CommonSearchAdapter()

    private var dataList = mutableListOf<CommonSearchItem>()

    var onHotWordsSelectedListener: OnHotWordsSelectedListener? = null

    init {
        val root = View.inflate(context, R.layout.common_search_view, this)
        binding = CommonSearchViewBinding.bind(root)
        val flexboxLayoutManager = FlexboxLayoutManager(context)
        flexboxLayoutManager.flexWrap = FlexWrap.WRAP
        flexboxLayoutManager.flexDirection = FlexDirection.ROW
        flexboxLayoutManager.alignItems = AlignItems.STRETCH
        flexboxLayoutManager.justifyContent = JustifyContent.FLEX_START
        binding.searchRecycler.apply {
            layoutManager = flexboxLayoutManager
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    outRect.bottom = ResDimension(R.dimen.convert_47px).toInt()
                }
            })
            adapter = commonSearchAdapter
        }
        commonSearchAdapter.setOnItemClickListener { adapter, view, position ->
            onHotWordsSelectedListener?.onHotWordsSelected(dataList[position].name)
        }

    }

    fun updateData(model: CommonSearchModel) {
        dataList.clear()
        dataList.addAll(model.data)
        commonSearchAdapter.setList(dataList)
    }

    interface OnHotWordsSelectedListener {
        fun onHotWordsSelected(hotWord: String)
    }
}