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.util.Log.d
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.ItemArticleRowFragmentBinding
import es.verdnatura.domain.ConstAndValues.SACADOR
import es.verdnatura.presentation.common.OnMistakeClickListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.OnQuantityClickListener
import es.verdnatura.presentation.common.OnSaleClickListener
import es.verdnatura.presentation.common.OnTicketClickListener
import es.verdnatura.presentation.common.onPackingClickListener
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.sacador.model.SaleVO


class SaleAdapter(
    private val items: List<SaleVO>,
    private val onPasillerosItemClickListener: OnPasillerosItemClickListener,
    private val onQuantityClick: OnQuantityClickListener,
    private val onSaleClickListener: OnSaleClickListener,
    private val onMistakeClickListener: OnMistakeClickListener,
    private val onPackingClick: onPackingClickListener,
    private var onTicketClick: OnTicketClickListener? = null,
    private var SaleAdapter: SaleAdapter? = null,
    private var type: String? = null,

    ) : RecyclerView.Adapter<SaleAdapter.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(

            ItemArticleRowFragmentBinding.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: ItemArticleRowFragmentBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(sale: SaleVO) {
            binding.apply {
                if (sale.pickedQuantity == null)
                    sale.pickedQuantity = 0

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

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


                itemArticlePlacements.apply {
                    layoutManager = childLayoutManager
                    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)
                }
                ticketFk.setOnClickListener {

                    if (onTicketClick != null) {
                        onTicketClick!!.onTicketClickListener(sale)
                    }

                }


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

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


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



                    if (sale.isPrepared == "1" || sale.isControlled == "1") {
                        sale.pickedQuantity = sale.quantity
                    }
                }
                // d("VERDNATURA::","La quantity de ${sale.saleFk} es ${sale.pickedQuantity} y está ${sale.isPrepared}")

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

                }
                //3969 Refactor collectionColors
                paintTicketcolor(sale.rgb, itemTicketColor)
                //paintTicketcolorOld(sale.level, itemTicketColor)

                val backgroundDrawableSac: Drawable = binding.itemArticleRowSemaforoSac.background
                val backgroundDrawablePre: Drawable = binding.itemArticleRowSemaforoPre.background
                val backgroundDrawableCon: Drawable = binding.itemArticleRowSemaforoCon.background

                if (!sale.isNew && sale.originalQuantity == sale.quantity) {
                    layoutError.visibility = View.GONE
                }


                //SEMAFORO
                if (sale.isPreviousPrepared == "1") {
                    DrawableCompat.setTint(
                        backgroundDrawablePre,
                        getColor(context!!, R.color.verdnatura_dark_sky_blue)
                    )
                    /*itemArticleRowSemaforoPre.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_dark_sky_blue
                        )
                    )*/
                } else {
                    DrawableCompat.setTint(
                        backgroundDrawablePre,
                        getColor(context!!, R.color.verdnatura_warm_grey)
                    )
                    /* itemArticleRowSemaforoPre.setBackgroundColor(
                         getColor(
                             context!!,
                             R.color.verdnatura_warm_grey
                         )
                     )*/
                }

                if (sale.isPrepared == "1") {
                    DrawableCompat.setTint(
                        backgroundDrawableSac,
                        getColor(context!!, R.color.verdnatura_pumpkin_orange)
                    )
                    /* itemArticleRowSemaforoSac.setBackgroundColor(
                         getColor(
                             context!!,
                             R.color.verdnatura_pumpkin_orange
                         )
                     )*/
                } else {
                    DrawableCompat.setTint(
                        backgroundDrawableSac,
                        getColor(context!!, R.color.verdnatura_warm_grey)
                    )
                    /* itemArticleRowSemaforoSac.setBackgroundColor(
                         getColor(
                             context!!,
                             R.color.verdnatura_warm_grey
                         )
                     )*/
                }



                if (sale.isControlled == "1") {

                    DrawableCompat.setTint(
                        backgroundDrawableCon,
                        getColor(context!!, R.color.verdnatura_dark_mint)
                    )
                    /*itemArticleRowSemaforoCon.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_dark_mint
                        )
                    )*/
                } else {
                    DrawableCompat.setTint(
                        backgroundDrawableCon,
                        getColor(context!!, R.color.verdnatura_warm_grey)
                    )
                    /*itemArticleRowSemaforoCon.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_warm_grey
                        )
                    )*/
                }


                if (sale.isControlled == "1") {
                    contentLayout.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_dark_mint
                        )
                    )
                } else if (sale.isPrepared == "1") {
                    contentLayout.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_pumpkin_orange
                        )
                    )
                } /*else if (sale.isPreviousPrepared == "1") {
                    contentLayout.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_dark_sky_blue
                        )
                    )
                }*/ else if (sale.isPreControlled == "1") {

                    contentLayout.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_dark_mint_light_precontrolled
                        )
                    )
                    DrawableCompat.setTint(
                        backgroundDrawableCon,
                        getColor(context!!, R.color.verdnatura_dark_mint_light_precontrolled)
                    )
                    /* itemArticleRowSemaforoCon.setBackgroundColor(
                         getColor(
                             context!!,
                             R.color.verdnatura_dark_mint_light_precontrolled
                         )
                     )*/
                } else if (sale.isPreviousPrepared == "1") {
                    contentLayout.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_dark_sky_blue
                        )
                    )
                } else {
                    contentLayout.setBackgroundColor(getColor(context!!, R.color.verdnatura_black))
                }


                //sergio: para de momento que pinten las lineas sin actualizar ni nada
                if (sale.isControlled == "2") {
                    DrawableCompat.setTint(
                        backgroundDrawableCon,
                        getColor(context!!, R.color.verdnatura_white)
                    )
                    /* itemArticleRowSemaforoCon.setBackgroundColor(
                         getColor(
                             context!!,
                             R.color.verdnatura_white
                         )
                     )*/
                    contentLayout.setBackgroundColor(
                        getColor(
                            context!!,
                            R.color.verdnatura_dark_mint_light
                        )
                    )
                }

                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) 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 = SaleAdapter(
                            sale.sonSales,
                            onPasillerosItemClickListener,
                            onQuantityClick,
                            onSaleClickListener,
                            onMistakeClickListener,
                            onPackingClick
                        )
                    }

                } else {
                    //revisar porque incosistencia
                    itemArticlePlacements.visibility = View.VISIBLE
                }


                /*  rvHeadlines.adapter=SaleAdapter(sale.sonSales,onPasillerosItemClickListener,onQuantityClick,onSaleClickListener,onMistakeClickListener,onPackingClick)
              rvHeadlines.visibility=View.VISIBLE
              rvHeadlines.layoutManager = LinearLayoutManager(context)}*/

                ivArrow.setOnClickListener {
                    d("VERDNATURA::", "click on line1 PADRE")
                    //Revisar lunes

                    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

                    //  isExpanded=!isExpanded
                }


                //ASIGNAMOS VALOR A LA VSITA
                this.sale = sale

            }
        }
    }


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

        if (color.isNullOrBlank()) {
            itemView.setBackgroundColor((Color.TRANSPARENT))
        } else {
            itemView.setBackgroundColor(Color.parseColor(color))
        }

    }

    private fun paintTicketcolorOld(color: String, itemView: View) {


        when (color.uppercase().trim()) {
            "ROJO" ->
                itemView.setBackgroundColor(Color.RED)

            "AMARILLO" ->
                itemView.setBackgroundColor(Color.YELLOW)

            "VERDE" -> itemView.setBackgroundColor(Color.GREEN)

            "AZUL" -> itemView.setBackgroundColor(Color.BLUE)

            "BLANCO" -> itemView.setBackgroundColor(Color.WHITE)

            "NEGRO" -> {

                itemView.setBackgroundColor(Color.BLACK)
                itemView.setBackgroundResource((R.drawable.border))
            }

            "VIOLETA" -> itemView.setBackgroundColor(0xFF4c2882.toInt())

            "GRIS" -> itemView.setBackgroundColor(Color.GRAY)

            "ORANGE" -> itemView.setBackgroundColor(0xFFFFBB33.toInt())

            "MORADO" -> itemView.setBackgroundColor(0xFFAA66CC.toInt())

            "CELESTE" -> itemView.setBackgroundColor(0xFF5b85F5.toInt())

            "ROSA" -> itemView.setBackgroundColor(0xFFfc0fc0.toInt())

            "DORADO" -> itemView.setBackgroundColor(0xFFb8860b.toInt())

            "MARRON" -> itemView.setBackgroundColor(0xFF663300.toInt())

            "PERLA" -> itemView.setBackgroundColor(0xFFcdcecf.toInt())

            "MARFIL" -> itemView.setBackgroundColor(0xFFf7eada.toInt())

            "CIAN" -> itemView.setBackgroundColor(0xFF00ffff.toInt())


            "BEIGE" -> itemView.setBackgroundColor(0xFFf2e7bf.toInt())

            else -> {
                itemView.setBackgroundColor(Color.TRANSPARENT)
                //itemView.setBackgroundResource(R.drawable.background_item_color)
                //  itemView.visibility=View.INVISIBLE
            }
        }
        // itemTicketColor.setBackgroundResource((R.drawable.rectangle))


    }
}