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

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentGeneralBlackBinding
import es.verdnatura.domain.ConstAndValues
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.GeneralAdapter
import es.verdnatura.presentation.common.GeneralItem
import es.verdnatura.presentation.common.OnCollectionSelectedListener
import es.verdnatura.presentation.common.OnGeneralItemRowClickListener
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.inventario.fragment.InventaryViewModel
import es.verdnatura.presentation.view.feature.workermistake.model.MistakeType


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class PackingMistakeFragment(var menuOrigin: String) :
    BaseFragment<FragmentGeneralBlackBinding, InventaryViewModel>(
        InventaryViewModel::class
    ) {

    private var goBack: Boolean = false
    private var onCollectionSelectedListener: OnCollectionSelectedListener? = null
    override fun getLayoutId(): Int = R.layout.fragment_general_black
    private var type = ""
    private var expeditionScan: String = ""
    private var listMistakes: ArrayList<GeneralItem> = ArrayList()
    private var listMistakesAdapter: GeneralAdapter? = null
    private lateinit var customDialogList: CustomDialogList

    companion object {
        fun newInstance(menuOrigin: String) = PackingMistakeFragment(menuOrigin = menuOrigin)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnCollectionSelectedListener) onCollectionSelectedListener = context
    }

    override fun init() {

        binding.scanInput.visibility = View.VISIBLE
        binding.scanInput.hint = getString(R.string.scanLabelExpedition)
        binding.mainToolbar.toolbarTitle.text = getString(R.string.titlePackingMistake)
        binding.splashProgress.visibility = View.GONE
        customDialogList = CustomDialogList(requireContext())

        setEvents()

        super.init()
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {

        type = ConstAndValues.VERTICKET
        super.onCreate(savedInstanceState)
    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                goBack = false
                if (!binding.scanInput.text.isNullOrEmpty()) {
                    binding.splashProgress.visibility = View.VISIBLE
                    expeditionScan = binding.scanInput.text.toString()
                    viewModel.expeditionMistakeType_get()
                }
                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }
    }

    override fun observeViewModel() {
        with(viewModel) {
            mistakeWorkerList.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = GONE
                showMistakeList(it.list)
            }

            responseAddMistake.observe(viewLifecycleOwner) {

                binding.splashProgress.visibility = GONE
                ma.messageWithSound(
                    if (it.isError) {
                        if (it.codeError == 403) {
                            getString(R.string.userNotPermission)
                        } else {
                            it.errorMessage
                        }

                    } else {
                        getString(R.string.errorCauseRegistered)
                    }, it.isError, true, isToasted = true
                )

            }
        }
    }

    private fun showMistakeList(list: List<MistakeType>) {
        binding.splashProgress.visibility = View.GONE
        listMistakes = ArrayList()
        list.forEach {
            listMistakes.add(GeneralItem(code = it.code, text = it.description))
        }

        customDialogList.setTitle(getString(R.string.errorCause) + expeditionScan)
            .setKoButton(
                getString(
                    R.string.cancel
                )
            ) {
                customDialogList.dismiss()
            }.hideDialog().show()


        listMistakesAdapter =
            GeneralAdapter(listMistakes, object : OnGeneralItemRowClickListener {
                override fun OnGeneralItemRowClickListener(item: GeneralItem) {
                    list.forEach {
                        if (it.description == item.text) {
                            binding.splashProgress.visibility = VISIBLE

                            try {
                                viewModel.expeditionMistake_add(
                                    vExpeditionFk = expeditionScan.toInt(),
                                    vTypeFk = item.code.toString()
                                )
                            } catch (ex: Exception) {
                                binding.splashProgress.visibility = GONE
                                ma.messageWithSound(
                                    getString(R.string.formatError),
                                    true,
                                    true,
                                    "",
                                    true
                                )
                            }
                            customDialogList.dismiss()
                        }
                    }

                }

            })

        customDialogList.getRecyclerView().adapter = listMistakesAdapter

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

    }
}

