package es.verdnatura.presentation.view.feature.smarttag.register


import android.content.Context
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import androidx.activity.OnBackPressedCallback
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentSacadorAssociatesmarttagBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnSmartTagRowClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.smarttag.adapter.SmartTagAdapter
import es.verdnatura.presentation.view.feature.smarttag.model.SmartTag
import es.verdnatura.presentation.view.feature.smarttag.sacador.fragment.SmartTagsViewModel

class RegisterSmartTagsFragment(
    var entryPoint: String = ""
) : BaseFragment<FragmentSacadorAssociatesmarttagBinding, SmartTagsViewModel>(
    SmartTagsViewModel::class
) {

    private var goBack: Boolean = false

    override fun getLayoutId(): Int = R.layout.fragment_sacador_associatesmarttag
    private lateinit var customDialog: CustomDialog
    private lateinit var customDialogList: CustomDialogList
    private var listSmartTags: ArrayList<SmartTag> = ArrayList()
    private var smartAdapter: SmartTagAdapter? = null
    private var itemScaned: String = ""


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


    override fun onAttach(context: Context) {
        super.onAttach(context)
        //  sergio: en test: Log.i("VERDNATURA:","attached")
        val callback: OnBackPressedCallback =
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    // Leave empty do disable back press or
                    // write your code which you want
                    //  Log.i("VERDNATURA:","PULSADO")

                }
            }
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            callback
        )

        //if (context is OnCollectionSelectedListener) onCollectionSelectedListener = context
    }


    override fun init() {

        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        goBack = false
        ma.hideBottomNavigation(GONE)
        binding.splashProgress.visibility = GONE

        setEvents()
        setToolBar()

        showScanSmartTags()
        super.init()
    }

    override fun onPause() {
        goBack = true
        super.onPause()
    }

    private fun setToolBar() {

        binding.mainToolbar.toolbarTitle.text = entryPoint
        binding.splashProgress.visibility = GONE

    }


    private fun bindShelving_add(shelvingOrSmarttag: String) {

        itemScaned = shelvingOrSmarttag

        if (listSmartTags.size > 0) {
            binding.splashProgress.visibility = VISIBLE
            viewModel.smartTagRegister(
                shelvingOrSmarttag,
                listSmartTags.first().code!!,
                listSmartTags.size.toString()
            )
            customDialogList.dismiss()
        }

        if (listSmartTags.isEmpty()) {
            val nameSmartTagwithWagon =
                getTextScaned(listSmartTags.size + 1) + itemScaned
            customDialogList.setTitle(getTextToPosition(listSmartTags.size + 1))


            listSmartTags.add(SmartTag(itemScaned, nameSmartTagwithWagon))
            smartAdapter!!.notifyDataSetChanged()
            customDialogList.setValue("")
        }
    }

    private fun add_item() {
        val nameSmartTagwithWagon: String

        nameSmartTagwithWagon =
            getTextScaned(listSmartTags.size + 1) + itemScaned
        customDialogList.setTitle(getTextToPosition(listSmartTags.size + 1))


        listSmartTags.add(SmartTag(itemScaned, nameSmartTagwithWagon))
        smartAdapter!!.notifyDataSetChanged()
        customDialogList.setValue("")
    }


    /* private fun scanRequest() {
         if (binding.scanInput != null) {
             binding.scanInput.requestFocus()
         }
         hideKeyboards()
     }*/

    /* private fun hideKeyboards() {
         try {
             requireActivity().hideKeyboard()
         } catch (e: Exception) {
         }
     }*/

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {

            customDialogList.dismiss()
            requireActivity().onBackPressed()

        }

    }


    override fun observeViewModel() {


        with(viewModel) {
            binding.splashProgress.visibility = GONE

            registerSmarttagNode.observe(viewLifecycleOwner) {

                if (it.isError) {
                    //listSmartTags.clear()
                    showScanSmartTags()
                    binding.splashProgress.visibility = GONE
                    ma.messageWithSound(it.errorMessage, true, false)
                } else {
                    add_item()
                    if (listSmartTags.size > 3) {

                        customDialog.setTitle(getString(R.string.info))
                            .setDescription(getString(R.string.registerOneWagoon))
                            .setOkButton(getString(R.string.accept))
                            {
                                listSmartTags.clear()
                                customDialog.dismiss()
                                showScanSmartTags()

                            }
                            .setKoButton(getString(R.string.exit)) {
                                customDialog.dismiss()
                                customDialogList.dismiss()
                                requireActivity().onBackPressed()

                            }
                            .show()

                    } else {
                        showScanSmartTags()
                    }
                    ma.messageWithSound(it.message, false, false)
                }
            }


            /*   responseadd.observe(viewLifecycleOwner) {

                   if (it.isError) {
                       ma.messageWithSound(it.errorMessage, true, false)

                   } else {
                       val nameSmartTagwithWagon: String

                       nameSmartTagwithWagon =
                           getTextScaned(listSmartTags.size + 1) + itemScaned
                       customDialogList.setTitle(getTextToPosition(listSmartTags.size + 1))


                       listSmartTags.add(SmartTag(itemScaned, nameSmartTagwithWagon))
                       smartAdapter!!.notifyDataSetChanged()
                       customDialogList.setValue("")

                   }
                   binding.splashProgress.visibility = GONE
               }*/

        }

    }

    private fun getTextToPosition(TagsScaned: Int): String {
        var message = ""

        when (TagsScaned) {
            0 -> message = getString(R.string.scanUpToDown)
            1 -> message = getString(R.string.scanHighLabel)
            2 -> message = getString(R.string.scanMedLabel)
            3 -> message = getString(R.string.scanLowLabel)
            4 -> message = getString(R.string.scannedWagon)
        }

        return message

    }

    private fun getTextScaned(TagScaned: Int): String {
        var message = ""

        when (TagScaned) {
            1 -> message = getString(R.string.scannedWagon)
            2 -> message = getString(R.string.highLabel)
            3 -> message = getString(R.string.midLabel)
            4 -> message = getString(R.string.lowLabel)
        }

        return message

    }

    private fun showScanSmartTags() {


        customDialogList.setTitle(getTextToPosition(listSmartTags.size))
            .setOkButton(getString(R.string.end)) {

                ma.hideKeyboard(customDialogList.getEditText())

                if (listSmartTags.size > 0) {

                    customDialogList.dismiss()
                    requireActivity().onBackPressed()


                } else {

                    customDialogList.dismiss()
                    requireActivity().onBackPressed()


                }

                /*   }.setKoButton("Deshacer") {
                       ma.hideKeyboard(customDialogList.getEditText())

                       if (!listSmartTags.isEmpty()) {

                           bindShelving_remove()

                       } else {
                           customDialogList.dismiss()
                           requireActivity().onBackPressed()

                       }*/


                //
            }.setValue("").show()

        customDialogList.getEditText().requestFocus()
        ma.hideKeyboard(customDialogList.getEditText())

        customDialogList.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5 || actionId == 6) {
                if (!customDialogList.getValue().isEmpty()) {
                    // Log.i("VERDNATURA:", "scan valor ${customDialogList.getValue()}")

                    if (listSmartTags.size > 3) {

                        customDialog.setTitle(getString(R.string.info))
                            .setDescription(getString(R.string.registerOneWagoon))
                            .setOkButton(getString(R.string.accept))
                            {
                                listSmartTags.clear()
                                customDialog.dismiss()
                                showScanSmartTags()

                            }
                            .setKoButton(getString(R.string.exit)) {
                                customDialog.dismiss()
                                customDialogList.dismiss()
                                requireActivity().onBackPressed()

                            }
                            .show()


                    } else {
                        bindShelving_add(customDialogList.getValue().uppercase())
                    }


                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }


        smartAdapter = SmartTagAdapter(listSmartTags, object : OnSmartTagRowClickListener {
            override fun OnSmartTagRowClickListener(item: SmartTag) {
            }
        }, showDelete = false)
        customDialogList.getRecyclerView().adapter = smartAdapter
        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)


    }


}



