package es.verdnatura.presentation.view.feature.collection.adapter

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat.getColor
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import es.verdnatura.R
import es.verdnatura.databinding.SaleRowFragmentBinding
import es.verdnatura.domain.ConstAndValues.SACADOR
import es.verdnatura.presentation.common.OnMistakeClickListener
import es.verdnatura.presentation.common.OnPackingClickSaleListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.OnQuantityClickSaleListener
import es.verdnatura.presentation.common.OnSaleClickSaleListener
import es.verdnatura.presentation.common.OnTicketClickSaleListener
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.sacador.model.Sale


class SaleAdapterNew(
    private val items: List<Sale>,
    private val onPasillerosItemClickListener: OnPasillerosItemClickListener,
    private val onQuantityClick: OnQuantityClickSaleListener,
    private val onSaleClickListener: OnSaleClickSaleListener,
    private val onMistakeClickListener: OnMistakeClickListener,
    private val onPackingClick: OnPackingClickSaleListener,
    private var onTicketClick: OnTicketClickSaleListener? = null,
    private var SaleAdapter: SaleAdapterNew? = null,
    private var type: String? = null,

    ) : RecyclerView.Adapter<SaleAdapterNew.AjustesItemHolder>() {
    var context: Context? = null
    var position: Int = 0

    var isExpanded: Boolean = type == "PRECHECKER"


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AjustesItemHolder {
        this.context = parent.context


        return AjustesItemHolder(

            SaleRowFragmentBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: AjustesItemHolder, position: Int) {
        this.position = position
        holder.bind(items[position])
    }

    inner class AjustesItemHolder(
        val binding: SaleRowFragmentBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(sale: Sale) {
            binding.apply {
                if (sale.reservedQuantity == null)
                    sale.reservedQuantity = 0

                val childLayoutManager =
                    LinearLayoutManager(context!!, RecyclerView.HORIZONTAL, false)

                val childLayoutManagerV =
                    LinearLayoutManager(context!!, RecyclerView.VERTICAL, false)


                itemArticlePlacements.apply {
                    layoutManager = childLayoutManager

                    // se quita porque ya no es necesario
                    // adapter = PlacementAdapter(sale.placements, onPasillerosItemClickListener)
                }

                //CLICK EVENTS
                contentLayout.setOnClickListener {
                    if (!sale.isParent) {
                        onSaleClickListener.onSaleClick(sale)
                    }
                }

              /*  itemArticleItemFk.setOnClickListener {
                    onPasillerosItemClickListener.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = binding.root.context.getString(R.string.titleItemConsult)
                        ), sale.itemFk.toString()
                    )
                }

                itemPackingItemFk.setOnClickListener {
                    onPackingClick.onPackingClick(sale)
                }

                itemArticleQuantity.setOnClickListener {
                    onQuantityClick.onQuantityClick(sale)
                }

                itemArticleQuantityPicked.setOnClickListener {
                    onQuantityClick.onQuantityClick(sale)
                }*/

               /* txtde.setOnClickListener {
                    onQuantityClick.onQuantityClick(sale)
                }*/

                packingTopicker.setOnClickListener {
                    //onQuantityClick.onQuantityClick(sale)

                }

                itemParkingCode.setOnClickListener {
                    onPackingClick.onPackingClick(sale)
                }
                itemArticleItemFkNew.setOnClickListener {
                    onPasillerosItemClickListener.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = binding.root.context.getString(R.string.titleItemConsult)
                        ), sale.itemFk.toString()
                    )
                }

                itemArticleFirstAccumulate.setOnClickListener {
                    //onQuantityClick.onQuantityClick(sale)
                }
                itemFirstToPicker.setOnClickListener {
                    onPackingClick.onPackingClick(sale)

                }
                quantityReserved.setOnClickListener{
                    onQuantityClick.onQuantityClick(sale)
                }

                linearLayoutItem.setOnClickListener {

                    println("El ticket es ${sale.ticketFk}")
                    if (onTicketClick != null) {
                        onTicketClick!!.onTicketClickListener(sale)
                    }

                }

                /*itemRowLayout.setOnLongClickListener{
                    onMistakeClickListener.onMistakeClickListener(sale)
                    false
                }*/

                imageErrorMessage.setOnClickListener {
                    //  onMistakeClickListener.onMistakeClickListener(sale)
                    false
                }


                //ERROR
                if (sale.originalQuantity != sale.saleQuantity && sale.originalQuantity != null) {
                    layoutError.visibility = View.VISIBLE
                    txtError.text =
                        binding.root.context.getString(R.string.originalQuantity) + sale.originalQuantity!!

                }

                if (sale.isAdded == 1) {
                    layoutError.visibility = View.VISIBLE
                    txtError.text = binding.root.context.getString(R.string.newItem)

                }

                paintTicketcolor(sale.rgb, itemTicketColor, sale.isPicked)

                if (sale.isAdded == 1 && sale.reservedQuantity != sale.saleQuantity) {
                    layoutError.visibility = View.GONE
                }

                if (sale.isPicked == 1) {
                    contentLayout.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_pumpkin_orange
                        )
                    )
                } else {
                    contentLayout.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_black
                        )
                    )

                }


                if (isExpanded) {
                    itemArticlePlacements.visibility = View.VISIBLE
                    ivArrow.setImageResource(R.drawable.ic_arrow_down)

                } else {
                    itemArticlePlacements.visibility = View.GONE
                    ivArrow.setImageResource(R.drawable.ic_arrow_up)
                }

                itemArticlePlacements.visibility = if (isExpanded) View.VISIBLE else {
                    View.GONE
                }

                if (sale.isParent) {
                   /* itemArticleItemFk.visibility = View.INVISIBLE
                    itemPackingText.visibility = View.INVISIBLE
                    itemPackingItemFk.visibility = View.INVISIBLE
                    itemArticleCel1.visibility = View.INVISIBLE
                    itemArticleCel2.visibility = View.INVISIBLE
                    itemArticleCel3.visibility = View.INVISIBLE
                    itemArticleQuantity.visibility = View.INVISIBLE
                    txtdeNew.visibility = View.INVISIBLE
                    itemArticleQuantityPicked.visibility = View.INVISIBLE
                    itemArticleQuantityLine3.visibility = View.VISIBLE*/
                    imageErrorMessage.visibility = View.INVISIBLE
                    ivArrow.visibility = View.VISIBLE


                } else {
                    /*itemArticleItemFk.visibility = View.VISIBLE
                    itemPackingText.visibility = View.VISIBLE
                    itemPackingItemFk.visibility = View.VISIBLE
                    itemArticleCel1.visibility = View.VISIBLE
                    itemArticleCel2.visibility = View.VISIBLE
                    itemArticleCel3.visibility = View.VISIBLE
                    itemArticleQuantity.visibility = View.VISIBLE
                    txtdeNew.visibility = View.VISIBLE
                    itemArticleQuantityPicked.visibility = View.VISIBLE
                    itemArticleQuantityLine3.visibility = View.VISIBLE*/
                    if (type != SACADOR) {
                        val colorRes =
                            if (sale.hasMistake == true) R.color.verdnatura_red_salix else R.color.verdnatura_black
                        imageErrorMessage.imageTintList =
                            ColorStateList.valueOf(getColor(context!!, colorRes))
                        imageErrorMessage.visibility = View.VISIBLE
                    } else {
                        imageErrorMessage.visibility = View.INVISIBLE
                    }
                    ivArrow.visibility = View.INVISIBLE
                }

                if (!sale.sonSales.isNullOrEmpty()) {
                    itemArticlePlacements.apply {
                        layoutManager = childLayoutManagerV
                        adapter = SaleAdapterNew(
                            sale.sonSales,
                            onPasillerosItemClickListener,
                            onQuantityClick,
                            onSaleClickListener,
                            onMistakeClickListener,
                            onPackingClick
                        )
                    }

                } else {
                    itemArticlePlacements.visibility = View.VISIBLE
                }

                ivArrow.setOnClickListener {

                    if (isExpanded!!) {
                        ivArrow.setImageResource(R.drawable.ic_arrow_up)
                        itemArticlePlacements.visibility = View.GONE
                    } else {

                        ivArrow.setImageResource(R.drawable.ic_arrow_down)
                        itemArticlePlacements.visibility = View.VISIBLE
                    }
                    isExpanded = !isExpanded

                }

                // previA NUEVA
                if (sale.saleGroupFk == null) {
                    previous.visibility = View.INVISIBLE
                } else {
                    previous.visibility = View.VISIBLE
                    previous.text = "${previous.text} ${sale.saleGroupFk}"
                }

                var result: Int
                var textToConcat: String

                result = sale.reservedQuantity % (sale.packing ?: sale.saleQuantity + 1)
                if (result != 0) {
                    textToConcat =
                        "${sale.reservedQuantity / (sale.grouping ?: 1)} x ${sale.grouping ?: "1"}"
                } else {
                    textToConcat =
                        "${sale.reservedQuantity / (sale.packing ?: 1)} pack de ${sale.packing ?: "1"}"
                }
               // binding.itemArticleCel2.text = textToConcat
                binding.packingTopicker.text = textToConcat

                var result2: Int
                var textToConcat2: String

                result2 = sale.accumulatedQuantity % (sale.packing ?: sale.saleQuantity + 1)
                if (result2 != 0) {
                    textToConcat2 =
                        "${(sale.saleQuantity - sale.accumulatedQuantity) / (sale.grouping ?: 1)} x ${sale.grouping ?: "1"}"
                } else {
                    textToConcat2 =
                        "${(sale.saleQuantity - sale.accumulatedQuantity) / (sale.packing ?: 1)} pack de ${sale.packing ?: "1"}"
                }


                if (sale.totalItemShelving > 1) {
                    binding.packingTopicker.text = textToConcat
                    binding.itemSecondToPicker.text = textToConcat2
                    binding.itemReservedNumber.text =
                        "${sale.currentItemShelving}/${sale.totalItemShelving}"

                  //  binding.itemSecond.text =
                   //     "${sale.saleQuantity - sale.accumulatedQuantity} de ${sale.saleQuantity}"
                    binding.itemArticleSecondAccumulate.text =
                        "${sale.saleQuantity - sale.accumulatedQuantity} de ${sale.saleQuantity}"
                    binding.selectToPicker.visibility = View.VISIBLE
                    binding.quantityReserved.text = "${sale.reservedQuantity}/${sale.saleQuantity}"
                } else {
                    binding.quantityReserved.text = "${sale.reservedQuantity}"
                   // binding.packingTopicker.text = ""
                    binding.itemReservedNumber.text = ""
                   // binding.itemSecond.text = ""
                    binding.itemArticleSecondAccumulate.text = ""
                    binding.itemSecondToPicker.text = ""
                    binding.selectToPicker.visibility = View.INVISIBLE

                } //segona linea començant per d'alt

                binding.selectToPicker.text =
                    "${sale.currentItemShelving}/${sale.totalItemShelving}"

                binding.itemArticleFirstAccumulate.text =
                    "${sale.reservedQuantity} de ${sale.saleQuantity}"



                this.sale = sale

            }
        }
    }


    private fun paintTicketcolor(color: String?, itemView: View, picked: Int) {

        if (color.isNullOrBlank()) {
            itemView.setBackgroundColor(
                if (picked == 0) {
                    (Color.TRANSPARENT)
                } else {
                    (context!!.getColor(R.color.verdnatura_pumpkin_orange))
                })
        } else {
            itemView.setBackgroundColor(Color.parseColor(color))
        }

    }

}