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

import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentAutomaticAddItemBinding
import es.verdnatura.domain.ConstAndValues.WAREHOUSEFK
import es.verdnatura.domain.isShelving
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnAutomaticItemClickListener
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.ubicador.adapter.AutomaticAdapter
import java.lang.Boolean.TRUE

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class AutomaticAddItemFragment(
    private var shelvingFk: String = "",
    private var titleAction: String? = null
) : BaseFragment<FragmentAutomaticAddItemBinding, UbicadorViewModel>(
    UbicadorViewModel::class
) {

    private var adapter: AutomaticAdapter? = null
    private var listItems: ArrayList<Long> = ArrayList()
    private var contador = 0
    private lateinit var customDialogList: CustomDialogList
    private var listShelvings: ArrayList<BarcodeVO> = ArrayList()
    private var listShelvingsAdapter: BarcodeAdapter? = null

    companion object {
        fun newInstance(entryPoint: String, titleAction: String) =
            AutomaticAddItemFragment(entryPoint, titleAction)
    }

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

    override fun init() {
        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text = titleAction
        setEvents()
        setViews()
        setToolBar()
        super.init()
    }

    private fun setToolBar() {
        binding.mainToolbar.toolbarSubtitle.visibility = View.VISIBLE
    }

    private fun setSubtitle() {
        binding.mainToolbar.toolbarSubtitle.text =
            getString(R.string.doubleText, getString(R.string.labels), contador.toString())
    }

    private fun setViews() {
        adapter = AutomaticAdapter(listItems, object : OnAutomaticItemClickListener {
            override fun onAutomaticItemClickListener(position: Int) {
                contador -= 1
                setSubtitle()
                if (listItems.size > position) {
                    listItems.removeAt(position)
                    adapter!!.notifyDataSetChanged()
                }

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

    private fun setEvents() {
        binding.editMatricula.requestFocus()
        binding.editMatricula.setOnEditorActionListener { v, actionId, event ->

            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (binding.editMatricula.text.toString().isNotEmpty()) {
                    contador += 1
                    setSubtitle()
                    try {
                        listItems.add(
                            0,
                            itemScanValue(
                                textScanned_filterDouble(binding.editMatricula.text.toString()),
                                arrayOf("buy"),
                                "more"
                            ).toString().toLong()

                        )
                        adapter!!.notifyItemInserted(0)
                        binding.itemsRecyclerview.scrollToPosition(0)
                    } catch (ex: Exception) {
                        ma.messageWithSound(ex.message.toString(), isError = true, isPlayed = true)
                    }
                }
                binding.editMatricula.setText("")
                ma.hideKeyboard(binding.editMatricula)
                return@setOnEditorActionListener true
            } else {
                ma.messageWithSound(
                    getString(R.string.diferentAction),
                    isError = true,
                    isPlayed = true
                )

            }

            return@setOnEditorActionListener false
        }

        binding.buttonFinalizar.setOnClickListener {
            if (listItems.isEmpty()) {
                ma.messageWithSound(
                    getString(R.string.scanItem),
                    isError = false,
                    isPlayed = false,
                    isToasted = true
                )
            } else {
                when (titleAction) {
                    getString(R.string.titleChecker) -> {
                        viewModel.itemShelvingAddList(
                            shelvingFk,
                            listItems.joinToString(),
                            TRUE,
                            mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
                        )
                    }

                    getString(R.string.addItemMultipleShelving) -> {
                        inputMultipleShelvingsForUbicator()
                    }

                    else -> {
                        viewModel.itemShelvingMakeMulti(
                            shelvingFk,
                            ArrayList(listItems),
                            mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
                        )
                    }
                }
            }
        }

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }
    }

    private fun inputMultipleShelvingsForUbicator() {
        if (listShelvings.isNotEmpty()) listShelvings.clear()
        customDialogList = CustomDialogList(requireContext())
        customDialogList.setTitle(
            getString(R.string.shelvingsLocate)
        )
        customDialogList.setDescription(
            getString(R.string.scanShelvingsLocate)
        ).setOkButton(getString(R.string.locate)) {

            listShelvings.forEach {
                viewModel.itemShelvingMakeMulti(
                    it.code!!,
                    ArrayList(listItems),
                    mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
                )

            }
            customDialogList.dismiss()

        }.setKoButton(getString(R.string.cancel)) {
            ma.hideKeyboard(customDialogList.getEditText())
            customDialogList.dismiss()

        }.setValue("").show()

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

        customDialogList.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (customDialogList.getValue().isNotEmpty()) {

                    try {
                        customDialogList.setValue(
                            itemScanValue(
                                customDialogList.getValue(), arrayOf("buy"), field = "id"
                            ).toString()
                        )
                        if (customDialogList.getValue().isShelving()) {
                            if (listShelvings.firstOrNull { it.code == customDialogList.getValue() } == null) {
                                listShelvings.add(BarcodeVO(code = customDialogList.getValue()))
                            } else {
                                throw Exception(getString(R.string.errorRepeatedShelving))
                            }
                        } else {
                            throw Exception()
                        }

                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            getString(R.string.errorInput),
                            isError = true,
                            isPlayed = true,
                            isToasted = true
                        )
                        listShelvings.removeAt(0)
                    }

                    listShelvingsAdapter!!.notifyItemChanged(0)
                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }

        listShelvingsAdapter = BarcodeAdapter(
            listShelvings, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {

                }
            }, showDelete = false
        )
        customDialogList.getRecyclerView().adapter = listShelvingsAdapter

        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

    }

    override fun observeViewModel() {
        with(viewModel) {
            responseUbicator.observe(viewLifecycleOwner) {
                ma.onMyBackPressed()
            }
        }
    }

}
