package es.verdnatura.presentation.view.feature.historicoarticulo.fragment

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat.getColor
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import es.verdnatura.R
import es.verdnatura.R.color.verdnatura_pumpkin_orange
import es.verdnatura.R.color.verdnatura_white
import es.verdnatura.databinding.FragmentHistoricoBinding
import es.verdnatura.domain.ConstAndValues.WAREHOUSEFK
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnClientHistoricItemClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.historicoarticulo.adapter.HistoricoAdapter
import es.verdnatura.presentation.view.feature.historicoarticulo.model.ItemHistoricoListVO
import es.verdnatura.presentation.view.feature.historicoarticulo.model.ItemHistoricoVO
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class HistoricoArticuloFragment(
    var itemFk: Int?
) : BaseFragment<FragmentHistoricoBinding, HistoricoArticuloViewModel>(
    HistoricoArticuloViewModel::class
) {
    private var adapter: HistoricoAdapter? = null
    private var listHistoric: ArrayList<ItemHistoricoVO> = ArrayList()
    private var listHistoryAux: ArrayList<ItemHistoricoVO> = ArrayList()
    private var filter: String = ""
    private var onpasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private lateinit var customDialog: CustomDialog

    companion object {
        fun newInstance(entryPoint: Int) = HistoricoArticuloFragment(entryPoint)
    }

    override fun getLayoutId(): Int = R.layout.fragment_historico

    override fun init() {

        ma.hideBottomNavigation(View.GONE)
        filter = "all"
        itemFk?.let {
            viewModel.itemGetBalance(
                it, mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
            )
        }
        binding.mainToolbar.toolbarTitle.text =
            getString(R.string.itemDiarySelected, itemFk.toString())
        setToolBar()
        setEvents()
        super.init()
    }

    override fun onAttach(context: Context) {
        if (context is OnPasillerosItemClickListener) onpasillerosItemClickListener = context
        super.onAttach(context)
    }

    private fun setToolBar() {

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconReload = ImageView(context)
        iconReload.setImageResource(R.drawable.ic_info_refresh)
        val iconGargabe = ImageView(context)
        iconGargabe.setImageResource(R.drawable.alpha_b_circle_outline)
        val iconFault = ImageView(context)
        iconFault.setImageResource(R.drawable.alpha_f_circle_outline)

        iconReload.tooltipText = getTooltip(R.drawable.ic_info_refresh)
        iconGargabe.tooltipText = getTooltip(R.drawable.alpha_b_circle_outline)
        iconFault.tooltipText = getTooltip(R.drawable.alpha_f_circle_outline)

        listIcons.add(iconGargabe)
        listIcons.add(iconFault)
        listIcons.add(iconReload)


        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {

                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {
                        iconReload.drawable -> viewModelwithFilter("all")
                        iconGargabe.drawable -> {
                            viewModelwithFilter("merma")
                            item.setTint(getColor(context!!, verdnatura_pumpkin_orange))
                        }

                        iconFault.drawable -> viewModelwithFilter("falta")
                    }

                    for (it in listIcons) {
                        if (it != item) {
                            it.drawable.setTint(getColor(context!!, verdnatura_white))
                        }
                    }
                    item.setTint(getColor(context!!, verdnatura_pumpkin_orange))

                    view?.performLongClick()
                }

            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)

    }

    private fun viewModelwithFilter(keyfilter: String) {
        filter = keyfilter
        itemFk?.let {
            viewModel.itemGetBalance(
                it, mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
            )
        }
    }

    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        binding.filterNameordateitem.setOnKeyListener { v, keyCode, event ->
            if (binding.filterNameordateitem.text.toString().isEmpty()) {
                if (listHistoric.size != listHistoryAux.size) {
                    listHistoric.removeAll(listHistoryAux.toSet())
                    listHistoryAux.forEach {
                        listHistoric.add(it)
                    }
                    adapter!!.notifyDataSetChanged()
                }

            } else {
                listHistoric.removeAll(listHistoryAux.toSet())
                listHistoryAux.forEach {

                    if (it.entityName?.contains(
                            binding.filterNameordateitem.text.toString(), true
                        ) == true
                    ) {
                        listHistoric.add(it)

                    }

                }

            }

            adapter!!.notifyDataSetChanged()
            return@setOnKeyListener false
        }

    }

    override fun observeViewModel() {
        with(viewModel) {
            loadHistoricoList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    listToAdapter(it.list, filter)
                    navigateToToday(it)

                }
            }
        }
    }

    private fun listToAdapter(lista: List<ItemHistoricoVO>, filter: String) {

        listHistoric.clear()
        listHistoryAux.clear()
        lista.forEach {
            if (filter == "all" || (filter == "falta" && it.entityName?.contains(
                    filter,
                    true
                ) == true) || (filter != "falta" && it.entityName?.contains(
                    "merma",
                    true
                ) == true && !it.entityName?.contains("falta", true)!!)
            ) {
                listHistoric.add(it)
            }
        }
        listHistoric.sortWith { item1, item2 ->
            val compareShipped = item1.shipped.compareTo(item2.shipped)
            //comentar con ivanm
            if (compareShipped == 0) {
                if (item1.order == null && item2.order == null) {
                    item2.balance!!.compareTo(item1.balance!!) // Comparar por balance cuando ambos órdenes son nulos
                } else if (item1.order == null) {
                    -1
                } else if (item2.order == null) {
                    1
                } else {
                    item2.order!!.compareTo(item1.order!!) // Invertir el orden
                }
            } else {
                compareShipped
            }
        }
        adapter = HistoricoAdapter(listHistoric, object : OnClientHistoricItemClickListener {

            override fun onClientHistoricItemClickListener(item: ItemHistoricoVO) {

                if (item.isTicket == 1) {
                    ma.onPasillerosItemClickListener(
                        PasillerosItemVO(
                            title = R.string.titleWebViewer,
                        ), entryPoint = Gson().toJson(
                            mutableMapOf(
                                "entryPoint" to item.originId,
                                "web" to "${
                                    mobileApplication.dataStoreApp.getServerSalix()
                                }/#!/ticket/${item.originId}/summary"
                            )
                        )
                    )
                } else {
                    customDialog = CustomDialog(requireContext())
                    customDialog
                        .setTitle(getString(R.string.entry))
                        .setDescription(item.originId.toString())
                        .setOkButton(
                            getString(
                                R.string.accept
                            )
                        ) {
                            customDialog.dismiss()
                        }

                        .show()

                }
            }
        })
        binding.historicoRecyclerview.adapter = adapter
        binding.historicoRecyclerview.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

        listHistoryAux.addAll(listHistoric)

    }

    private fun navigateToToday(it: ItemHistoricoListVO) {
        var positionToday = 0
        val sdf = SimpleDateFormat(getString(R.string.dateFormat), Locale.getDefault())
        val currentDate = sdf.format(Date())

        for (item in it.list) {
            if (currentDate == item.shipped) {
                break
            }
            positionToday += 1
        }

        binding.historicoRecyclerview.scrollToPosition(positionToday)
    }

}