package com.remax.visualnovel.ui.chat.ui.expandableSelector

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.drake.brv.annotaion.DividerOrientation
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.divider
import com.drake.brv.utils.grid
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.remax.visualnovel.R
import com.remax.visualnovel.databinding.LayoutItemSettingBackgroundBinding
import com.remax.visualnovel.databinding.LayoutSettingBgSubViewBinding
import com.remax.visualnovel.entity.response.ChatBackground
import com.remax.visualnovel.extension.glide.load

class ExpandBackgroundSubView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    private lateinit var items: List<ChatBackground>
    private var mBinding: LayoutSettingBgSubViewBinding


    init {
        mBinding = LayoutSettingBgSubViewBinding.inflate(LayoutInflater.from(context), this, true)
        with(mBinding) {
            initRv(itemsRv)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initRv(itemsRv: RecyclerView) {
        itemsRv.grid(3)
            .divider {
                setDivider(10, true)
                orientation = DividerOrientation.VERTICAL
            }.setup {
                addType<ChatBackground>(R.layout.layout_item_setting_background)

                onClick(R.id.root) {
                    val chatBackground = getModel<ChatBackground>()
                    if (!chatBackground.select) {
                        itemsRv.bindingAdapter.models?.filterIsInstance<ChatBackground>()?.forEach { item ->
                            item.select = item == chatBackground
                        }
                        itemsRv.bindingAdapter.notifyDataSetChanged()
                    }
                }

                onBind {
                    val item = getModel<ChatBackground>()
                    with(getBinding<LayoutItemSettingBackgroundBinding>()) {
                        if (!item.imgUrl.isNullOrEmpty()) {
                            //ivBackgroundSrc.load(item.imgUrl)
                        }
                        ivDel.visibility = if (item.deletable) VISIBLE else GONE

                        ivUpload.isVisible = item.isUploadLocalItem
                        ivBackgroundSrc.isVisible = !item.isUploadLocalItem
                    }
                }
            }
    }

    fun setItems(newItems: List<ChatBackground>) {
        items = newItems
        mBinding.itemsRv.models = items
    }


}