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.FragmentExpeditionScanBinding
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.common.OnScanLongClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.component.CustomDialogTwoButtons
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.ExpeditionScanAdapter
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionScanList
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionScanVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionTruckVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemPalletVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemScanList

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ExpeditionScanFragment(
    private var itemExpeditionTruckVO: ItemExpeditionTruckVO? = null,
    private var itemPalletVO: ItemPalletVO? = null
) : BaseFragment<FragmentExpeditionScanBinding, ExpeditionScanViewModel>(
    ExpeditionScanViewModel::class
) {

    private var adapter: ExpeditionScanAdapter? = null
    private var onPalletClickListener: OnPalletClickListener? = null
    private var onComprobarPalletViewClickListener: OnComprobarPalletViewClickListener? = null
    private lateinit var customDialogList: CustomDialogList
    private lateinit var customDialogTwoButtons: CustomDialogTwoButtons

    private var listExpeditions: ArrayList<BarcodeVO> = ArrayList()
    private var expeditionAdapter: BarcodeAdapter? = null
    private lateinit var customDialog: CustomDialog
    var mperror: MediaPlayer? = null

    companion object {
        fun newInstance(item: ItemExpeditionTruckVO, itemPalletVO: ItemPalletVO) =
            ExpeditionScanFragment(item, itemPalletVO)
    }

    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_scan

    override fun onCreate(savedInstanceState: Bundle?) {
        mperror = MediaPlayer.create((activity as MainActivity), R.raw.error)

        super.onCreate(savedInstanceState)
    }

    override fun init() {
        println("ExpeditionScanFragment")
        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        customDialogTwoButtons = CustomDialogTwoButtons(requireContext())
        binding.expeditionScanDetailPallet.text = getString(
            R.string.expeditionInfo, getString(R.string.pallet), itemPalletVO!!.Pallet.toString()
        )
        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text =
            getString(R.string.expeditionInfo, itemExpeditionTruckVO?.eta.orEmpty(), itemExpeditionTruckVO?.description.orEmpty())
        setToolBar()
        setEvents()
        viewModel.expeditionScanList(
            itemPalletVO!!.Pallet
        )
        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.expeditionScanList(itemPalletVO!!.Pallet)
                    } else if (item == iconPlus) {
                        viewModel.expeditionScanAdd(
                            vPalletFk = itemPalletVO!!.Pallet, vTruckFk = itemExpeditionTruckVO!!.id
                        )

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


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

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

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

        }
    }

    private fun printExpeditionList(it: ItemExpeditionScanList) {

        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        adapter = ExpeditionScanAdapter(it.list, object : OnScanLongClickListener {
            override fun onScanLongClickListener(itemExpeditionScanVO: ItemExpeditionScanVO) {
                customDialogTwoButtons.setTitle(
                    getString(R.string.ticket) + itemExpeditionScanVO.Ticket + getString(
                        R.string.pallet
                    ) + itemPalletVO!!.Pallet
                ).setDescription(getString(R.string.expedit) + itemExpeditionScanVO.expeditionFk)
                    .setOkButton(getString(R.string.delete)) {
                        viewModel.expeditionScanDel(
                            itemExpeditionScanVO.id, itemPalletVO!!.Pallet
                        )
                        customDialogTwoButtons.dismiss()
                    }.setKoButton(getString(R.string.cancel)) {
                        customDialogTwoButtons.dismiss()
                    }.show()
            }

        })
        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.pallet) + " " + itemPalletVO!!.Pallet + " \n(" + 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.ok
                            )
                        ) {
                            customDialog.dismiss()
                        }.show()
                }

                customDialogList.dismiss()

            }.setKoButton(getString(R.string.close)) {
                ma.hideKeyboard(customDialogList.getEditText())
                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 {
                        listExpeditions.add(BarcodeVO(code = customDialogList.getValue()))
                        viewModel.expeditionScanPut(
                            it.list[0].palletFk, customDialogList.getValue().toInt()
                        )

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

                        expeditionAdapter!!.notifyItemInserted(listExpeditions.size - 1)
                    } catch (ex: Exception) {
                        getString(R.string.errorInput)
                    }

                }
                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)

    }

}