package com.develop.step.widgets

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.develop.food.base.repo.entity.DevRecipePortionSize
import com.develop.food.base.ui.FullScreenTransparentDialog
import com.develop.step.R
import com.develop.step.databinding.DialogAmountSelectBinding

class AmountSelectDialog(
    private val data: List<DevRecipePortionSize>,
    private val onSelect: (data: DevRecipePortionSize) -> Unit
): FullScreenTransparentDialog() {

    private lateinit var binding: DialogAmountSelectBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DialogAmountSelectBinding.inflate(
            inflater, container, false
        )
        binding.ivCancel.setOnClickListener {
            removeSelf()
        }
        binding.root.setOnClickListener {
            removeSelf()
        }
        val wrappers = mutableListOf<Wrapper>()
        data.forEach {
            wrappers.add(Wrapper(it, false))
        }
        binding.clLayer.adapter = Adapter(wrappers).apply {
            setOnItemClickListener { adapter, view, position ->
                for (wrapper in wrappers) {
                    wrapper.selected = false
                }
                val data = adapter.data[position] as Wrapper
                data.selected = true
                onSelect(data.data)
                adapter.notifyDataSetChanged()
            }
        }
        return binding.root
    }

    class Adapter(data: MutableList<Wrapper>): BaseQuickAdapter<Wrapper, BaseViewHolder>(
        R.layout.item_cook_portion_size_item, data
    ) {
        override fun convert(holder: BaseViewHolder, item: Wrapper) {
            val tvJars = holder.getView<View>(R.id.tv_jars)
            holder.setText(R.id.tv_jars, item.data.portionSize + " JAR")
            tvJars.isSelected = item.selected
        }
    }

    class Wrapper(
        val data: DevRecipePortionSize,
        var selected: Boolean
    )
}