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

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat.getColor
import androidx.core.graphics.drawable.DrawableCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import es.verdnatura.R
import es.verdnatura.databinding.SaleRowFragmentBinding
import es.verdnatura.domain.ConstAndValues.PREITEMPICKERTEST
import es.verdnatura.domain.ConstAndValues.PREPARED
import es.verdnatura.domain.ConstAndValues.SACADOR
import es.verdnatura.domain.toast
import es.verdnatura.presentation.common.OnMistakeClickListener
import es.verdnatura.presentation.common.OnPackingClickSaleListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
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 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

                }

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


                packingTopicker.setOnClickListener {
                    // Solo se cambia la cantidad al cogerla no al pulsar !!
                    // onQuantityClick.onQuantityClick(sale)

                }

                itemParkingCode.setOnClickListener {
                    onPackingClick.onPackingClick(sale)
                }
                itemCode.setOnClickListener {
                    onPackingClick.onPackingClick(sale)
                }

                itemArticleLongInfo.setOnClickListener {
                    onPasillerosItemClickListener.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = R.string.titleItemConsult
                        ), sale.itemFk.toString()
                    )
                }

                itemArticleItemFkNew.setOnClickListener {
                    onPasillerosItemClickListener.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = 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)
                    }

                }
                println("type es $type")

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

                //ERROR
                println("Sacador sale item ${sale.itemFk} sale ${sale.saleFk} cantidad ${sale.saleQuantity} original ${sale.originalQuantity}")

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

                } else {
                    layoutError.visibility = View.GONE
                }

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

                paintTicketcolor(sale.rgb, binding.itemTicketColor.background)

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


                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*/
                    packingTopicker.visibility = View.INVISIBLE
                    quantityReserved.visibility = View.INVISIBLE
                    itemArticleItemFkNew.visibility = View.INVISIBLE

                    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*/

                    imageErrorMessage.visibility = View.GONE
                    if (type != SACADOR && type != PREITEMPICKERTEST) {
                        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,
                            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 = "PREV:" + sale.saleGroupFk
                }

                var result: Int
                var textToConcat: String

                try {

                    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.packingTopicker.text = textToConcat

                    val textToConcat2: String

                    val result2: Int =
                        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.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.itemReservedNumber.text = ""

                        binding.itemArticleSecondAccumulate.text = ""
                        binding.itemSecondToPicker.text = ""
                        binding.selectToPicker.visibility = View.INVISIBLE

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

                } catch (ex: Exception) {
                    ex.message!!.toast(context)
                }


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

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

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

                }

                binding.itemParkingCode.text =
                    if (type == PREITEMPICKERTEST) sale.parkingCodePrevia else sale.parkingCode


                this.sale = sale

            }
        }
    }

    private fun paintTicketcolor(color: String?, backgroundDrawableTicket: Drawable) {

        if (color.isNullOrBlank()) {
            DrawableCompat.setTint(
                backgroundDrawableTicket, Color.TRANSPARENT
            )
        } else {
            DrawableCompat.setTint(
                backgroundDrawableTicket, Color.parseColor(color)
            )

        }
    }

}