package com.adealink.weparty.share.poster

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.module.profile.data.UserPlaymateSkill
import com.adealink.weparty.share.R
import com.adealink.weparty.share.databinding.DialogPosterChooseCategoryBinding
import com.adealink.weparty.share.poster.adapter.CategoryItem
import com.adealink.weparty.share.poster.adapter.CategoryItemViewBinder

class PosterChooseCategoryDialog : BottomDialogFragment(R.layout.dialog_poster_choose_category),
    CategoryItemViewBinder.CategoryChooseListener {

    private val binding by viewBinding(DialogPosterChooseCategoryBinding::bind)
    private val listAdapter by fastLazy { MultiTypeListAdapter<CategoryItem>() }

    private var list: List<CategoryItem> = emptyList()

    private var selectedListener: ((list: List<UserPlaymateSkill>) -> Unit)? = null
    fun setCategoryList(list: List<UserPlaymateSkill>, selected: List<UserPlaymateSkill>) {
        this.list = list.map {
            CategoryItem(it, selected.contains(it))
        }
    }

    fun setSelectListener(listener: (list: List<UserPlaymateSkill>) -> Unit) {
        selectedListener = listener
    }

    override fun initViews() {
        super.initViews()
        listAdapter.register(CategoryItemViewBinder(this))
        binding.rvCategory.adapter = listAdapter
        binding.rvCategory.layoutManager =
            LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        listAdapter.submitList(list)

        binding.btnConfirm.onClick {
            val selectedList = list.filter { it.selected }.map { it.data }
            if (selectedList.isEmpty()) {
                showToast(R.string.share_poster_skill_at_least_select_one)
                return@onClick
            }
            selectedListener?.invoke(selectedList.take(3))
            dismiss()
        }
    }

    override fun onChoose(item: CategoryItem, position: Int) {
        val nextSelected = !item.selected
        if (nextSelected) {
            val selectedList = list.filter { it.selected }.map { it.data }
            if (selectedList.size == 3) {
                showToast(R.string.share_poster_skill_at_most)
                return
            }
        }
        item.selected = nextSelected
        listAdapter.notifyItemChanged(position)
    }

}