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

import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat.getColor
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
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.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
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 java.text.SimpleDateFormat
import java.util.*


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class HistoricoArticuloFragment(
    var itemFk: String = ""
) : BaseFragment<FragmentHistoricoBinding, HistoricoArticuloViewModel>(
    HistoricoArticuloViewModel::class
) {
    private var adapter: HistoricoAdapter? = null

    // private lateinit var customDialogInput: CustomDialogInput
    // private lateinit var customDialog: CustomDialog
    private var listHistoric: ArrayList<ItemHistoricoVO> = ArrayList()
    private var listHistoryAux: ArrayList<ItemHistoricoVO> = ArrayList()
    private var filter: String = ""

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

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

    override fun init() {

        // customDialogInput = CustomDialogInput(requireContext())
        // customDialog = CustomDialog(requireContext())
        ma.hideBottomNavigation(View.GONE)
        filter = "all"
        viewModel.itemDiary(getData(USER), getData(PASSWORD), itemFk, getData(WAREHOUSEFK))
        binding.mainToolbar.toolbarTitle.text = getString(R.string.itemdiary) + ":" + itemFk
        setToolBar()
        setEvents()

        super.init()
    }


    private fun setToolBar() {

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconReload.tooltipText = getTooltip(R.drawable.ic_transaction)
            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("contenedor")
                            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
        binding.splashProgress.visibility = View.VISIBLE
        viewModel.itemDiary(getData(USER), getData(PASSWORD), itemFk, getData(WAREHOUSEFK))
    }

    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

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

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


                    if (it.name.contains(
                            binding.filterNameordateitem.text.toString(),
                            true
                        )
                    ) {
                        //Log.i("VERDNATURA:","si contiene ${filter_nameordateitem.text.toString()}")
                        listHistoric.add(it)

                    }
                }

            }


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

    }

    override fun observeViewModel() {
        with(viewModel) {
            loadHistoricoList.observe(viewLifecycleOwner, Observer { event ->
                event.getContentIfNotHandled().notNull {

                    binding.splashProgress.visibility = View.GONE
                    listToAdapter(it.list, filter)
                    navigateToToday(it)

                }
            })
        }
    }


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

        listHistoric.clear()
        listHistoryAux.clear()
        lista.forEach {

            if (filter.equals("all")) {
                listHistoric.add(it)
                //  listHistoryAux.add(it)
            } else {

                if (it.name.contains(filter, true)) {
                    listHistoric.add(it)
                    //   listHistoryAux.add(it)
                }
            }

        }

        adapter = HistoricoAdapter(listHistoric)
        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))
        val currentDate = sdf.format(Date())

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

        binding.historicoRecyclerview.scrollToPosition(positionToday)
    }

}