package com.develop.common.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.develop.base.ext.updateText
import com.develop.base.mvvm.FullScreenTransparentDialog
import com.develop.common.data_repo.db.entity.DevRecipePortionSize
import com.develop.common.databinding.DialogAmountSelectBinding
import com.drake.brv.utils.linear
import com.drake.brv.utils.setup
import com.develop.common.R
import com.drake.brv.utils.models

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.apply {
            linear()
            setup {
                addType<Wrapper>(R.layout.item_cook_portion_size_item)
                onBind {
                    val tvJar = findView<TextView>(R.id.tv_jars)
                    val model = getModel<Wrapper>()
                    tvJar.updateText(model.data.portionSize + " JAR")
                    tvJar.isSelected = model.selected
                }
                R.id.tv_jars.onClick {
                    for (wrapper in wrappers) {
                        wrapper.selected = false
                    }
                    val data = getModel<Wrapper>()
                    data.selected = true
                    onSelect(data.data)
                    notifyDataSetChanged()
                }
            }
        }.models = wrappers
        return binding.root
    }

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