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

import android.content.Context
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentExpeditionPalletBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.OnComprobarPalletViewClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPalletClickListener
import es.verdnatura.presentation.view.component.CustomDialog
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.inventario.adapter.ToolBarAdapter
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.paletizador.adapter.ExpeditionPalletAdapter
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionTruckVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemPalletListVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemPalletVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemScanList

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ExpeditionPalletFragment(
    var itemExpeditionTruckVO: ItemExpeditionTruckVO? = null
) : BaseFragment<FragmentExpeditionPalletBinding, ExpeditionScanViewModel>(
    ExpeditionScanViewModel::class
) {

    private var adapter: ExpeditionPalletAdapter? = null
    private var onPalletClickListener: OnPalletClickListener? = null
    private var onComprobarPalletViewClickListener: OnComprobarPalletViewClickListener? = null
    private lateinit var customDialogList: CustomDialogList
    private var listExpeditions: ArrayList<BarcodeVO> = ArrayList()
    private var expeditionAdapter: BarcodeAdapter? = null
    private lateinit var customDialog: CustomDialog
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null

    companion object {
        fun newInstance(item: ItemExpeditionTruckVO) = ExpeditionPalletFragment(item)
    }

    override fun onAttach(context: Context) {
        if (context is OnPalletClickListener) onPalletClickListener = context
        if (context is OnComprobarPalletViewClickListener) onComprobarPalletViewClickListener =
            context
        super.onAttach(context)
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        println("ExpeditionPalletFragment")
        mperror = MediaPlayer.create((activity as MainActivity), R.raw.error)
        mpok = MediaPlayer.create((activity as MainActivity), R.raw.ok)
        super.onCreate(savedInstanceState)
    }

    override fun init() {
        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text = getString(
            R.string.expeditionInfo,
            itemExpeditionTruckVO!!.eta,
            itemExpeditionTruckVO!!.description
        )
        setToolBar()
        setEvents()
        viewModel.expeditionPalletList(
            itemExpeditionTruckVO!!.id
        )

        super.init()
    }

    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

    }

    private fun setToolBar() {
        val listIcons: ArrayList<Drawable> = ArrayList()
        val iconReload: Drawable =
            ResourcesCompat.getDrawable(resources, R.drawable.ic_autorenew_black_24dp, null)!!
        val iconPlus: Drawable =
            ResourcesCompat.getDrawable(resources, R.drawable.ic_add_black_24dp, null)!!
        listIcons.add(iconReload)
        listIcons.add(iconPlus)
        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapter(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    if (item == iconReload) {
                        viewModel.expeditionPalletList(
                            itemExpeditionTruckVO!!.id
                        )
                    } else if (item == iconPlus) {
                        viewModel.expeditionScanAdd(
                            vPalletFk = 0, vTruckFk = itemExpeditionTruckVO!!.id
                        )
                    }
                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    override fun observeViewModel() {
        with(viewModel) {
            loadExpeditionPalletList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull { printExpeditionList(it) }
            }

            loadScanList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull { showScanExpeditions(it) }
            }

            responseExpeditionAddHasNotSameRoute.observe(viewLifecycleOwner) {
                if (it) {
                    mperror?.start()

                }
            }
            loadResponseScanPut.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    listExpeditions.add(0, BarcodeVO(code = responseScanPut.value.toString()))
                    customDialogList.setDescription(getString(R.string.total) + listExpeditions.size)
                    expeditionAdapter!!.notifyItemInserted(0)
                }
            }

        }

    }

    private fun printExpeditionList(it: ItemPalletListVO) {
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        adapter = ExpeditionPalletAdapter(
            it.list,
            onPalletClickListener!!,
            onComprobarPalletViewClickListener!!,
            itemExpeditionTruckVO!!
        )
        binding.expeditionPalletRecyclerview.adapter = adapter
        binding.expeditionPalletRecyclerview.layoutManager = lm

    }

    private fun showScanExpeditions(it: ItemScanList) {

        listExpeditions = ArrayList()
        it.list.forEach {
            if (it.expeditionFk != "0") listExpeditions.add(BarcodeVO(code = it.expeditionFk))
        }

        customDialogList.setTitle(getString(R.string.expeditionP) + binding.mainToolbar.toolbarTitle.text + ")")
            .setOkButton(
                getString(
                    R.string.test
                )
            ) {
                ma.hideKeyboard(customDialogList.getEditText())


                if (listExpeditions.size > 0) {
                    onComprobarPalletViewClickListener!!.onComprobarPalletViewClickListener(
                        itemExpeditionTruckVO!!, ItemPalletVO(Pallet = it.list[0].palletFk)
                    )
                } else {
                    customDialog.setTitle(getString(R.string.info))
                        .setDescription(getString(R.string.expeditionsError))
                        .setOkButton(getString(R.string.accept)) {
                            customDialog.dismiss()
                        }.show()
                }
                customDialogList.dismiss()

            }.setKoButton(getString(R.string.close)) {
                ma.hideKeyboard(customDialogList.getEditText())
                viewModel.expeditionPalletList(
                    itemExpeditionTruckVO!!.id
                )
                listExpeditions = ArrayList()
                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 {

                        viewModel.expeditionScanPut(
                            it.list[0].palletFk, customDialogList.getValue().toInt()
                        )
                        viewModel.checkRouteExpeditionScanPut(
                            it.list[0].palletFk, customDialogList.getValue().toInt()
                        )

                    } catch (e: Exception) {
                        if (mperror != null) mperror!!.start()
                    }



                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }

        expeditionAdapter = BarcodeAdapter(listExpeditions, object : OnBarcodeRowClickListener {
            override fun onBarcodeRowClickListener(item: BarcodeVO) {

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

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

    }

}