package es.verdnatura.presentation.view.feature.boxPicking

import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import es.verdnatura.R
import es.verdnatura.databinding.FragmentGeneralBlackBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnCollectionSelectedListener
import es.verdnatura.presentation.common.hideKeyboard
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.feature.delivery.model.ExpeditionSalix
import es.verdnatura.presentation.view.feature.delivery.model.Expeditions
import es.verdnatura.presentation.view.feature.delivery.viewmodels.DeliveryViewModel

class BoxPickingFragment(var title: String) :
    BaseFragment<FragmentGeneralBlackBinding, DeliveryViewModel>(DeliveryViewModel::class) {
    private var onCollectionSelectedListener: OnCollectionSelectedListener? = null
    private var isBoxScanned: Boolean = false
    private lateinit var customDialogInput: CustomDialogInput
    private var codeStateId: Number = 0
    override fun getLayoutId(): Int = R.layout.fragment_general_black

    companion object {
        fun newInstance(title: String) = BoxPickingFragment(title = title)
    }

    override fun init() {

        binding.mainToolbar.toolbarTitle.text = title
        setEvents()
        customDialogInput = CustomDialogInput(requireContext())
        viewModel.getExpeditionStateId("CHECKED")
        super.init()
    }

    private fun setEvents() {
        binding.scanInput.visibility = VISIBLE
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }
        binding.scanInput.hint = getString(R.string.scanLabelExpedition)
        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()) {
                    try {

                        viewModel.findExpedition(
                            expedition = itemScanValue(
                                binding.scanInput.text.toString(),
                                arrayOf("expedition"),
                                "id"
                            ).toString().toLong(),
                            expeditionStateId = codeStateId
                        )

                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            message = getString(R.string.itemNotValid),
                            isError = true,
                            isPlayed = true,
                            isToasted = false
                        )
                    }

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

    private fun showScanBarcode(expeditionFk: Long) {
        try {

            customDialogInput.setTitle(getString(R.string.scanItem))
                .setOkButton(getString(R.string.accept)) {
                    if (customDialogInput.getValue().isNotEmpty()) {
                        viewModel.isBoxPickingInPrintOut(
                            expeditionFk = expeditionFk,
                            customDialogInput.getValue()
                        )

                    }
                    customDialogInput.dismiss()
                }

                .setKoButton(getString(R.string.cancel)) {
                    customDialogInput.setValue("")
                    customDialogInput.dismiss()

                }.setValue("").show()


            customDialogInput.getEditText().setOnEditorActionListener { _, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                    if (customDialogInput.getValue().isNotEmpty()) {
                        viewModel.isBoxPickingInPrintOut(
                            expeditionFk = expeditionFk,
                            itemScanValue(
                                customDialogInput.getValue(), arrayOf("buy"), "more"
                            ).toString()
                        )
                    }
                    customDialogInput.dismiss()
                    binding.scanInput.requestFocus()
                    return@setOnEditorActionListener true
                }
                false
            }

        } catch (ex: Exception) {
            getString(R.string.errorInput)
        }
        customDialogInput.getEditText().requestFocus()
    }

    override fun observeViewModel() {
        with(viewModel) {
            responseExpeditionStateId.observe(viewLifecycleOwner) {
                codeStateId = it
            }
            responseFindExpeditionId.observe(viewLifecycleOwner) { it ->
                if (it != 0) {
                    showScanBarcode(it.toLong())
                } else {
                    ma.messageWithSound(
                        getString(
                            R.string.errorBoxPicking
                        ), isError = true, isPlayed = true, isToasted = true
                    )
                }
            }
            responseStateAdd.observe(viewLifecycleOwner) {
                if (it) {
                    ma.messageWithSound(message = "", isPlayed = true, isError = false)
                    customDialogInput.dismiss()
                    binding.scanInput.requestFocus()
                }
            }

            isBoxPickingInPrintOut.observe(viewLifecycleOwner) {

                if (it.expeditionFk.toInt() == 0) {
                    ma.messageWithSound(
                        message = getString(R.string.errorBoxpicking),
                        isError = true,
                        isPlayed = true,
                        isToasted = false
                    )
                } else {
                    viewModel.expeditionStateAddSalix(
                        expeditions = Expeditions(
                            arrayListOf(
                                ExpeditionSalix(
                                    expeditionFk = it.expeditionFk.toInt(),
                                    stateCode = "CHECKED",
                                    isScanned = 1
                                )
                            )
                        )
                    )
                }

                binding.scanInput.requestFocus()
                hideKeyboard()

            }

            responseCode.observe(viewLifecycleOwner) {

                ma.messageWithSound(
                    message = getString(R.string.errorInput),
                    isError = true,
                    isPlayed = true,
                    isToasted = null

                )
                binding.scanInput.requestFocus()

            }
        }
    }

}

