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

import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentAutomaticAddExpeditionBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnAutomaticItemClickListener
import es.verdnatura.presentation.common.itemScanValue
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
import es.verdnatura.presentation.view.feature.ubicador.adapter.AutomaticAdapter

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ExpeditionPreparedStateFragment(var codeState: String = "PREPARED", var title: String = "") :
    BaseFragment<FragmentAutomaticAddExpeditionBinding, DeliveryViewModel>(
        DeliveryViewModel::class
    ) {

    private var adapter: AutomaticAdapter? = null
    private var contador = 0
    private var isScanned = false
    private val listExpeditions: ArrayList<ExpeditionSalix> = arrayListOf()
    private var expeditionStateTypeId: Number = 0

    companion object {
        fun newInstance(codeState: String, title: String) =
            ExpeditionPreparedStateFragment(codeState = codeState, title = title)

        fun newInstance() = ExpeditionPreparedStateFragment()
    }

    override fun getLayoutId(): Int = R.layout.fragment_automatic_add_expedition
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
    }

    override fun onDestroyView() {
        super.onDestroyView()
        activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }

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

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

    private fun setSubtitle() {
        binding.mainToolbar.toolbarSubtitle.text =
            getString(R.string.countNumber, getString(R.string.label), listExpeditions.size)
    }

    private fun setViews() {
        adapter =
            AutomaticAdapter(listExpeditions.map { it.expeditionFk.toLong() } as ArrayList<Long>,
                object : OnAutomaticItemClickListener {
                    override fun onAutomaticItemClickListener(position: Int) {

                        if (listExpeditions.size > position) {
                            listExpeditions.removeAt(position)
                        }
                        adapter!!.updateItems(listExpeditions.map { it.expeditionFk.toLong() } as ArrayList<Long>)
                        setSubtitle()
                    }
                })
        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) {
                isScanned =
                    event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER
                if (binding.editMatricula.text.toString().isNotEmpty()) {
                    try {
                        val itemScaned = itemScanValue(
                            textScanned_filterDouble(binding.editMatricula.text.toString()),
                            arrayOf("expedition"),
                            "id"
                        ).toString().toLong()
                        if (!(listExpeditions.any { it.expeditionFk == itemScaned })) {
                            viewModel.findExpedition(
                                itemScaned, expeditionStateTypeId
                            )
                            binding.itemsRecyclerview.scrollToPosition(0)
                        } else {
                            ma.messageWithSound(
                                message = getString(R.string.boxDuplicated),
                                isError = true,
                                isPlayed = true,
                                isToasted = true
                            )
                        }
                    } 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 (listExpeditions.isNotEmpty())
                viewModel.expeditionStateAddSalix(
                    Expeditions(
                        listExpeditions
                    )
                ) else ma.onMyBackPressed()
        }

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

    override fun observeViewModel() {
        with(viewModel) {
            responseStateAdd.observe(viewLifecycleOwner) {
                ma.onMyBackPressed()
            }
            responseExpeditionStateId.observe(viewLifecycleOwner) {
                expeditionStateTypeId = it
            }

            responseFindExpeditionId.observe(viewLifecycleOwner) {

                if (it != 0) {
                    listExpeditions.add(
                        ExpeditionSalix(
                            expeditionFk = it,
                            stateCode = codeState,
                            isScanned = if (isScanned) 1 else 0
                        )
                    )
                    setSubtitle()
                    adapter!!.updateItems(listExpeditions.map { it.expeditionFk.toLong() } as ArrayList<Long>)
                } else {
                    ma.messageWithSound(
                        if (codeState == "PREPARED") getString(R.string.expeditionPrepared) else getString(
                            R.string.errorBoxPicking
                        ),
                        isError = true,
                        isPlayed = true,
                        isToasted = true
                    )
                }
            }
        }
    }
}

