package com.adealink.weparty.playmate.findpartner.comp

import android.view.Gravity
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.OrientationHelper
import com.adealink.frame.base.fastLazy
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.weparty.commonui.ext.dp
import com.adealink.weparty.commonui.recycleview.adapter.MultiTypeListAdapter
import com.adealink.weparty.commonui.recycleview.layoutmanager.FlowLayoutManager
import com.adealink.weparty.playmate.databinding.LayoutFindPartnerOptionBinding
import com.adealink.weparty.playmate.findpartner.adapter.OptionItemViewBinder
import com.adealink.weparty.playmate.findpartner.data.OptionData
import com.adealink.weparty.playmate.findpartner.data.OptionItemData

class FindPartnerOptionsComp(
    lifecycleOwner: LifecycleOwner,
    val title: String,
    val options: List<OptionData>,
    val binding: LayoutFindPartnerOptionBinding
) : ViewComponent(lifecycleOwner) {

    companion object {
        const val SPAN_COUNT = 4
    }

    private val optionAdapter by fastLazy { MultiTypeListAdapter<OptionItemData>() }
    private val optionItemList = mutableListOf<OptionItemData>()
    override fun onCreate() {
        super.onCreate()
        initView()
    }

    private fun initView() {
        binding.tvTitle.text = title

        binding.rvOptions.adapter = optionAdapter
        binding.rvOptions.layoutManager =
            FlowLayoutManager(OrientationHelper.VERTICAL, Gravity.START, 8.dp(), 10.dp())
//        binding.rvOptions.layoutManager =
//            GridLayoutManager(
//                context,
//                SPAN_COUNT, RecyclerView.VERTICAL, false
//            )
        optionAdapter.register(OptionItemViewBinder(object :
            OptionItemViewBinder.OnOptionsSelectListener {
            override fun onSelected(option: OptionItemData) {
                onOptionChoose(option)
            }
        }))
        optionItemList.addAll(options.map { OptionItemData(it) })
        optionAdapter.submitList(optionItemList)
    }

    private fun onOptionChoose(option: OptionItemData) {
        for (data in optionItemList) {
            data.data.selected = (data == option)
        }
        optionAdapter.notifyDataSetChanged()
    }

    fun reset() {
        for ((index, data) in optionItemList.withIndex()) {
            data.data.selected = index == 0
        }
        optionAdapter.notifyDataSetChanged()
    }

}