package es.verdnatura.presentation.view.feature.category

import android.graphics.drawable.Drawable
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentChangeCategoryBinding
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogInputTwoValues
import es.verdnatura.presentation.view.feature.articulo.model.ItemDetails

//Tarea #4940
class ChangeCategoryFragment(var entrypoint: String) :
    BaseFragment<FragmentChangeCategoryBinding, ChangeCategoryViewModel>(
        ChangeCategoryViewModel::class
    ) {

    override fun getLayoutId(): Int = R.layout.fragment_change_category
    private var barCodeScanned: Long = 0
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogDetails: CustomDialogInputTwoValues
    private lateinit var myItemDetail: ItemDetails
    private val listIcons: ArrayList<ImageView> = ArrayList()
    private var isScannedForDetails = false

    companion object {
        fun newInstance(entrypoint: String) = ChangeCategoryFragment(entrypoint = entrypoint)
    }

    override fun init() {

        customDialogInput = CustomDialogInput(requireContext())
        customDialogDetails = CustomDialogInputTwoValues(requireContext())
        binding.mainToolbar.toolbarTitle.text = entrypoint
        scanShelving()
        setEvents()
        setToolBar()

        super.init()
    }

    private fun setToolBar() {

        val iconReset = ImageView(context)
        iconReset.setImageResource(R.drawable.ic_autorenew_black_24dp)
        listIcons.add(iconReset)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {

                        iconReset.drawable -> {
                            scanShelving()
                        }

                    }
                }

            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        binding.mainToolbar.toolbarIcons.visibility = View.VISIBLE
    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }
        binding.quantity.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                binding.price.requestFocus()
                true
            } else {
                false
            }
        }
        binding.quantity.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                binding.quantity.setSelection(binding.quantity.text.length)
            }
        }

        binding.price.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                binding.price.setSelection(binding.price.text.length)
            }
        }
        binding.price.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                ma.hideKeyboard(binding.price)
                binding.btnChangeCategory.performClick()
                true
            } else {
                false
            }
        }
        customDialogDetails.setOnDismissListener {
            if (!isScannedForDetails) ma.onMyBackPressed()
        }

        binding.btnChangeCategory.setOnClickListener {
            try {
                if (myItemDetail.visible < binding.quantity.text.toString().toInt()) {
                    ma.messageWithSound(
                        getString(R.string.quantityBigger), isPlayed = true, isError = true
                    )
                } else {
                    if (myItemDetail.itemCost < binding.price.text.toString().toDouble()) {
                        ma.messageWithSound(
                            getString(R.string.priceBigger), isPlayed = true, isError = true
                        )

                    } else {
                        viewModel.itemDevalueA2(
                            itemFk = binding.itemFK.text.toString().toLong(),
                            shelvingFk = binding.shelvingFK.text.toString(),
                            buyingValue = binding.price.text.toString().toDouble(),
                            quantity = binding.quantity.text.toString().toInt()
                        )
                    }
                }
            } catch (ex: Exception) {
                ma.messageWithSound(
                    message = ex.message!!.toString(), isError = true, isPlayed = true
                )
            }

        }

    }

    override fun observeViewModel() {
        with(viewModel) {

            itemDetails.observe(viewLifecycleOwner) { item ->

                if (item.itemFk == null) {
                    scanShelving()
                    customDialogDetails.getEditText().requestFocus()

                } else {
                    myItemDetail = item

                    binding.itemFK.setText(item.itemFk.toString())
                    binding.shelvingFK.setText(item.vShelvingFK.uppercase())
                    binding.price.setText((if (item.itemCost == 0.0) item.itemCost else item.itemCost / 2).toString())
                    binding.quantity.setText(
                        item.visible.toString()
                    )
                    binding.quantity.requestFocus()
                    binding.quantity.setSelection(binding.quantity.text.length)
                    customDialogDetails.dismiss()
                }

            }
            responseDevalue.observe(viewLifecycleOwner) {
                if (it == true) {
                    scanShelving()
                } else {
                    isScannedForDetails = false
                    scanShelving()
                    resetTxt()

                }
            }

        }
    }

    private fun resetTxt() {
        binding.itemFK.setText("")
        binding.shelvingFK.setText("")
        binding.price.setText("")
        binding.quantity.setText("")
    }

    private fun scanShelving() {

        customDialogDetails.getEditText().requestFocus()
        customDialogDetails.setTitle(getString(R.string.titleChangeCategory))
        customDialogDetails.setDescription(getString(R.string.scanItemShelving))
        customDialogDetails.setInfoTex(getString(R.string.scanItem))
        customDialogDetails.setInfoTextTwo(getString(R.string.scanSmarttagOrShelving))
        customDialogDetails.setValue("")
        customDialogDetails.setValueTwo("")

            .setOkButton(getString(R.string.itemDetails)) {

                if (customDialogDetails.getValue().isNotEmpty() && customDialogDetails.getValueTwo()
                        .isNotEmpty()
                ) {

                    getInfoForA2(
                        customDialogDetails.getValue().toLong(), customDialogDetails.getValueTwo()
                    )
                }

            }.setKoButton(getString(R.string.cancel)) {
                customDialogDetails.dismiss()
                ma.onMyBackPressed()
            }.show()

        customDialogDetails.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                customDialogDetails.setValue(
                    itemScanValue(
                        customDialogDetails.getValue(), arrayOf("buy"), "more"
                    ).toString()
                )

                return@setOnEditorActionListener false
            }
            false
        }

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

                if (customDialogDetails.getValue().isNotEmpty() && customDialogDetails.getValueTwo()
                        .isNotEmpty()
                ) {
                    getInfoForA2(
                        customDialogDetails.getValue().toLong(), customDialogDetails.getValueTwo()
                    )
                }

                return@setOnEditorActionListener true
            }
            false
        }

        customDialogDetails.setFocusText()
    }

    private fun getInfoForA2(barCode: Long, shelvingFK: String) {
        isScannedForDetails = true
        try {
            viewModel.itemShelvingGetItemDetails(
                barcode = barCode, shelvingFk = shelvingFK
            )

        } catch (ex: Exception) {
            getString(R.string.errorInput).toast(requireActivity())
        }
        customDialogDetails.setValue("")
    }

}


