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

import android.annotation.SuppressLint
import android.content.Context
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentReubicationCollectionBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.OnReubicationClickListener
import es.verdnatura.presentation.view.component.CustomDialogInputTwoValues
import es.verdnatura.presentation.view.component.CustomDialogThreeButtons
import es.verdnatura.presentation.view.feature.reubication.adapter.ReubicatorAdapter
import es.verdnatura.presentation.view.feature.reubication.model.Reubication
import es.verdnatura.presentation.view.feature.ubicador.fragment.UbicadorViewModel


//Tarea #3754
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ReubicationCollectionFragment(
    var list: MutableList<Reubication>,
    var shelving: String
) : BaseFragment<FragmentReubicationCollectionBinding, UbicadorViewModel>(
    UbicadorViewModel::class
) {
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var adapter: ReubicatorAdapter? = null
    private lateinit var customDialogThreeButtons: CustomDialogThreeButtons
    private lateinit var customDialogInputTwoValues: CustomDialogInputTwoValues
    private lateinit var listItems: ArrayList<Reubication>

    companion object {
        fun newInstance(
            entryPoint: MutableList<Reubication>,
            shelving: String
        ): ReubicationCollectionFragment {

            return ReubicationCollectionFragment(entryPoint, shelving)
        }
    }

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

    override fun onAttach(context: Context) {
        //sergio: necesario para pasarle el context al recyclerViewer
        if (context is OnPasillerosItemClickListener) pasillerosItemClickListener = context
        super.onAttach(context)
    }

    @SuppressLint("SetTextI18n")
    override fun init() {
        // customDialogThreeButtons = CustomDialogThreeButtons(requireContext())
        customDialogInputTwoValues = CustomDialogInputTwoValues(requireContext())
        ma.hideBottomNavigation(GONE)
        binding.splashProgress.visibility = GONE
        binding.mainToolbar.toolbarTitle.text =
            "${getString(R.string.wagoon)}:${shelving.uppercase()}"
        setEvents()

        showList(list.sortedBy { it.pickingOrder } as MutableList<Reubication>)
        super.init()
    }


    private fun showList(list: MutableList<Reubication>) {

        //sergio:ponemos paréntesis y la matrícula
        //sergio: mirar de ordenar no solo por el picking order de un elemento si no de todos*/

        for (item in list) {
            item.code = shelving.uppercase()
            for (i in item.carros) {
                i.visible = "(" + i.visible + ")"
            }
            if (item.carros.size == 0) {
                item.pickingOrder = 0
            } else {
                item.pickingOrder = item.carros[0].pickingOrder
            }
        }

        adapter = ReubicatorAdapter(list.sortedBy { it.pickingOrder },
            pasillerosItemClickListener!!,
            object :
                OnReubicationClickListener {
                override fun onReubicationClick(reubication: Reubication) {
                    //binding.splashProgress.visibility = VISIBLE
                    showLeaveItemDialog(reubication)


                }

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

    }

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

        binding.collectionSwipe.setOnRefreshListener {

            callItemShelvingReturn()
            binding.collectionSwipe.isRefreshing = false

        }

        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                if (!binding.scanInput.text.isNullOrEmpty()) {
                    if (list.isNotEmpty()) {
                        scanPlate(binding.scanInput.text.toString().uppercase())
                    } else {
                        shelving = binding.scanInput.text.toString().uppercase()
                        callItemShelvingReturn()
                    }
                }

                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }


    }

    private fun scanPlate(plate: String) {
        //showLeaveItemDialog(plate)
        var found = false
        all_list@ for (items in list) {

            for (placements in items.carros) {


                if (placements.shelvingFk == plate) {
                    found = true
                    showLeaveItemDialog(items)
                    break@all_list

                }


            }
        }
        if (!found) {
            ma.messageWithSound(
                getString(R.string.itemScanetNotFound),
                true,
                true,
                isToasted = true
            )
        }
    }

    private fun showLeaveItemDialog(itemReubication: Reubication) {

        val messageDescrip =
            getString(R.string.scanPlateToLeave) + itemReubication.itemFk + "-" + itemReubication.longName

        customDialogInputTwoValues.setEnableValue(false)

        customDialogInputTwoValues.setDescription(messageDescrip)
            .setValue(itemReubication.quantity)
            .setOkButton(getString(R.string.leaveItem)) {


                if (customDialogInputTwoValues.getValueTwo().isNotEmpty()) {
                    binding.splashProgress.visibility = VISIBLE
                    viewModel.itemShelving_merge(
                        getData(USER),
                        getData(PASSWORD),
                        itemReubication.id,
                        customDialogInputTwoValues.getValueTwo().uppercase()
                    )
                } else {
                    ma.messageWithSound(
                        getString(R.string.returnScan),
                        true,
                        true,
                        isToasted = true
                    )
                }
                customDialogInputTwoValues.setValueTwo("")
                customDialogInputTwoValues.dismiss()

            }.setKoButton(getString(R.string.cancel)) {
                binding.splashProgress.visibility = GONE
                customDialogInputTwoValues.setValueTwo("")
                scanRequest()
                customDialogInputTwoValues.dismiss()
            }.show()
        //}
        customDialogInputTwoValues.getEditTextTwo()
            .setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {

                    if (customDialogInputTwoValues.getValueTwo().isNotEmpty()) {

                        binding.splashProgress.visibility = VISIBLE
                        viewModel.itemShelving_merge(
                            getData(USER),
                            getData(PASSWORD),
                            itemReubication.id,
                            customDialogInputTwoValues.getValueTwo().uppercase()
                        )
                    }
                    customDialogInputTwoValues.setValue("")
                    scanRequest()
                    customDialogInputTwoValues.dismiss()
                    //hideKeyboards()
                    return@setOnEditorActionListener true
                }
                false
            }

        customDialogInputTwoValues.setFocusTextTwo()

    }


    private fun scanRequest() {
        binding.scanInput.requestFocus()

    }

    override fun observeViewModel() {
        with(viewModel) {


            loadReubicationList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = GONE


                    if (it.list.isEmpty()) {

                        ma.messageWithSound(
                            getString(R.string.successReubication), false, true, getString(
                                R.string.info
                            )
                        )
                        ma.onBackPressed()
                    } else {
                        if (it.list[0].isError) {
                            ma.messageWithSound(
                                it.list[0].errorMessage, true, true, getString(
                                    R.string.info
                                )
                            )
                        } else {
                            showList(it.list)
                        }
                    }

                }
            }

            response.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = GONE

                if (it.isError) {

                    ma.messageWithSound(it.errorMessage, true, true)

                } else {

                    ma.messageWithSound(it.response, false, false, "", false)

                    callItemShelvingReturn()

                }
            }

        }
    }

    private fun callItemShelvingReturn() {
        binding.splashProgress.visibility = VISIBLE

        viewModel.itemShelving_return(
            usuario = getData(USER),
            password = getData(PASSWORD),
            shelvingFk = shelving,

            )

    }

    /* private fun createReubications(list: MutableList<Reubication>) {

         *//*  val listItems = mutableListOf<String>()
          val reubication = mutableListOf<Reubication>()

          for (item in list) {
              if (!listItems.contains(item.itemFk)) {
                  listItems.add(item.itemFk)
                  reubication.add(
                      Reubication(
                          itemFk = item.itemFk,
                          longName = item.longName,
                          visible = item.visible,
                          shelvingFk = item.shelvingFk
                      )
                  )
              }
          }

          for (item in list) {
              for (r in reubication) {
                  if (item.itemFk == r.itemFk) {

                      if (item.shelvingFk.uppercase() != shelving.uppercase())
                          r.carros.add(
                              PlacementReubication(
                                  code = item.code,
                                  plate = item.shelvingFk,
                                  visible = "(" + item.visible + ")",
                                  idItemShelving = item.id
                              )
                          )
                  }
              }
          }

          for (item in list) {
              Log.d("VERDNATURA::", "el item es " + item.itemFk + "-" + item.id + "-" + item.visible)
              for (r in item.carros) {
                  Log.d(
                      "VERDNATURA::",
                      "la reubic es" + r.idItemShelving + "-" + r.plate + "-" + r.code
                  )
              }
          }
          //ma.openFragmentReubications(reubication,shelving)
  *//*
        showList(list)
    }*/

}