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

import android.content.Context
import android.graphics.drawable.Drawable
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.ReposicionFragmentBinding
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
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.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.presacador.model.PreSacadorItemVO
import es.verdnatura.presentation.view.feature.reposicion.adapter.ReposicionAdapter
import es.verdnatura.presentation.view.feature.sacador.model.PlacementSupplyListVO
import es.verdnatura.presentation.view.feature.sacador.model.SaleVO


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ReposicionFragment : BaseFragment<ReposicionFragmentBinding, ReposicionViewModel>(
    ReposicionViewModel::class
) {

    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null

    private lateinit var customDialog: CustomDialog
    private lateinit var customDialogList: CustomDialogList
    private lateinit var customDialogInput: CustomDialogInput

    private var sales: ArrayList<PreSacadorItemVO> = ArrayList()

    private var lm: LinearLayoutManager? = null
    private var saleAdapter: ReposicionAdapter? = null

    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null

    private var storedBackPosition: Int = 0
    private var storedShelvingPosition: Int = 0
    private var storedPosition: Int = 0
    private var listPlacementSupply: ArrayList<BarcodeVO> = ArrayList()
    private var itemShelvingFkStored: String = ""
    private var placementSupplyAdapter: BarcodeAdapter? = null

    private var goBack: Boolean = false
    private var goBack2: Boolean = false

    companion object {
        fun newInstance() = ReposicionFragment()
    }

    override fun onAttach(context: Context) {
        if (context is OnPasillerosItemClickListener) pasillerosItemClickListener = context
        super.onAttach(context)
    }

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

    override fun init() {
        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        ma.hideBottomNavigation(View.GONE)
        binding.splashProgress.visibility = View.GONE
        binding.mainToolbar.toolbarTitle.text = getString(R.string.itemPlacementSupplyGetOrder)
        setToolBar()
        setEvents()
        super.init()
    }

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

        super.onCreate(savedInstanceState)
    }

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


    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        binding.btnObtener.setOnClickListener {
            binding.splashProgress.visibility = View.VISIBLE
            viewModel.itemPlacementSupplyGetOrder(
                usuario = getData(USER),
                password = getData(PASSWORD),
                sectorFk = getData(SECTORFK)

            )
        }

        binding.btnCancelar.setOnClickListener {

            customDialog.setTitle(getString(R.string.confirm)).setDescription(getString(R.string.closeOdrder))
                .setKoButton(getString(R.string.close)) {
                    scanRequest()
                    customDialog.dismiss()
                }.setOkButton(getString(R.string.close)) {
                binding.splashProgress.visibility = View.VISIBLE
                if (sales.count() > 0) {
                    viewModel.itemPlacementSupplyCloseOrder(
                        usuario = getData(USER),
                        password = getData(PASSWORD),
                        id = sales[0].id,
                        quantity = sales[0].quantity.toString()
                    )
                }
                customDialog.dismiss()

            }.show()


        }

        //ESCANER =========
        hideKeyboards()
        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!binding.scanInput.text.toString().isNullOrEmpty()) {

                    if (sales.count() > 0 && sales[0].saldo == 0) {
                        getString(R.string.orderCompleted).toast(requireContext())
                    } else {
                        findSale(binding.scanInput.text.toString())
                    }


                }
                binding.scanInput.setText("")
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            true
        }

        hideKeyboards()


        //LISTA =========
        binding.collectionSwipe.setOnRefreshListener {
            binding.splashProgress.visibility = View.VISIBLE
            viewModel.itemPlacementSupplyGetOrder(
                usuario = getData(USER),
                password = getData(PASSWORD),
                sectorFk = getData(SECTORFK)

            )
            binding.collectionSwipe.isRefreshing = false
        }

    }

    private fun hideKeyboards() {
        requireActivity().hideKeyboard()
    }

    override fun observeViewModel() {
        with(viewModel) {
            salesList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                createSaleList(it)
            })

            placementSuppleyList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (!goBack) printShelvingResult(it)
                goBack = false
            })

            responseCode.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (!goBack2) {
                    if (it.isError) {
                        customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage)
                            .setKoButton(getString(R.string.close)) {
                                scanRequest()
                                customDialog.dismiss()
                            }.show()
                    } else {
                        if (checkItemScan(it.response)) {
                            scanRequest()
                            customDialogList.dismiss()
                            mpok?.start()
                            onQuantityOfShelvingSelected(itemShelvingFkStored)
                        } else {
                            customDialogList.setValueTwo("")
                            // showErrorMessage("El resultado del procedimiento barcodeToItem de la etiqueta escaneada es: " +it.response)
                            showErrorMessage(getString(R.string.lineNotExist))
                            mperror?.start()
                        }
                    }
                }

                goBack2 = false

            })

            responseClose.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                sales.clear()
                saleAdapter!!.notifyDataSetChanged()
                binding.btnCancelar.visibility = View.GONE
            })
        }


        super.observeViewModel()
    }

    private fun createSaleList(salesList: List<PreSacadorItemVO>) {
        binding.splashProgress.visibility = View.GONE
        if (salesList.isNullOrEmpty()) {
            customDialog.setTitle(getString(R.string.titleReplacement)).setDescription(getString(R.string.NotOrderReplacement))
                .setKoButton(getString(R.string.cancel)) {
                    if (sales.count() > 0) {
                        sales.clear()
                        saleAdapter!!.notifyDataSetChanged()
                    }
                    customDialog.dismiss()
                }.show()
            binding.scanInput.visibility = View.GONE
            binding.btnCancelar.visibility = View.GONE
        } else if (salesList.count() > 0 && salesList[0].saldo == 0) {
            getString(R.string.orderCompleted).toast(requireContext())
            binding.scanInput.visibility = View.GONE
            binding.btnCancelar.visibility = View.GONE
        } else {

            binding.scanInput.visibility = View.VISIBLE
            binding.btnCancelar.visibility = View.VISIBLE

            sales = ArrayList()
            salesList.forEach {
                sales.add(it)
            }
            lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

            saleAdapter = ReposicionAdapter(sales, pasillerosItemClickListener!!, object :
                OnSaleClickListener {
                override fun onSaleClick(sale: SaleVO) {
                    sales.forEachIndexed { index, saleVO ->
                        if (saleVO.idMovimiento == sale.saleFk) {
                            if (saleVO.quantity != saleVO.picked) {
                                showScanner(index, saleVO)
                            } else {
                                unMarkLine(index)
                            }
                        }
                    }
                }
            })
            binding.fragmentSacadorCollections.adapter = saleAdapter
            binding.fragmentSacadorCollections.layoutManager = lm

        }
    }


    //SEARCH AND MARK
    private fun findSale(txtscan: String) {
        var index = 0
        var isBreak = false
        var isOk = false

        for (saleVO in sales) {
            if (saleVO.quantity != saleVO.picked) {
                //1- Por carro
                var shelvingIndex = 0
                for (placementVO in saleVO.carros) {
                    if (txtscan.uppercase() == placementVO.shelving.uppercase()) {
                        if (mpok != null) mpok!!.start()
                        isOk = true
                        showShelving(index, shelvingIndex)
                        isBreak = true
                        break
                    }
                    shelvingIndex += 1
                }
                if (isBreak) break
            }
            index += 1
        }

        if (!isOk) {
            mperror!!.start()
            (getString(R.string.itemScanetNotFound) + txtscan).toast(requireContext())
        }

    }

    private fun findSale(txtscan: String, position: Int) {
        var index = 0
        var isBreak = false
        var isOk = false

        val saleVO = sales[position]

        if (saleVO.quantity != saleVO.picked) {
            //1- Por carro
            var shelvingIndex = 0
            for (placementVO in saleVO.carros) {
                if (txtscan.uppercase() == placementVO.shelving.uppercase()) {
                    if (mpok != null) mpok!!.start()
                    isOk = true
                    showShelving(position, shelvingIndex)
                    isBreak = true
                    break
                }
                shelvingIndex += 1
            }
        }
        index += 1


        if (!isOk) {
            mperror!!.start()
            (getString(R.string.itemScanetNotFound) + txtscan).toast(requireContext())
        }

    }

    //SHELVINGS
    private fun showShelving(position: Int, shelvingPosition: Int) {
        storedShelvingPosition = shelvingPosition
        storedPosition = position
        binding.splashProgress.visibility = View.VISIBLE
        var quantityGet = "0"
        try {
            quantityGet = (sales[position].saldo - sales[position].picked).toString()
        } catch (e: Exception) {
        }
        viewModel.itemPlacementSupplyAiming(
            usuario = getData(USER),
            password = getData(PASSWORD),
            itemFk = sales[position].itemFk,
            quantity = quantityGet,
            shelvingFk = sales[position].carros[shelvingPosition].shelving
        )
    }

    private fun printShelvingResult(placementSupplyListVO: PlacementSupplyListVO) {
        var shelving = ""
        var item = ""
        var longName = ""
        var total = "0"
        var itemShelvingFk = "0"
        if (!placementSupplyListVO.list.isEmpty()) {
            val placement = placementSupplyListVO.list[0]
            shelving = placement.shelving
            item = placement.itemFk
            longName = placement.longName
            total = placement.total
            itemShelvingFk = placement.itemShelvingFk
        }
        listPlacementSupply = ArrayList()
        placementSupplyListVO.list.forEach {
            listPlacementSupply.add(BarcodeVO(code = it.proposal))
        }

        customDialogList.setTitle("$shelving($item) $total "+getString(R.string.de)+" $longName").setOkButton(getString( R.string.take)) {
            if (customDialogList.getValueTwo().isNotEmpty()) {
                if (checkItemScan(customDialogList.getValueTwo())) {
                    onQuantityOfShelvingSelected(itemShelvingFk)
                    mpok?.start()
                    customDialogList.dismiss()
                } else {
                    itemShelvingFkStored = itemShelvingFk
                    binding.splashProgress.visibility = View.VISIBLE
                    viewModel.getIdFromCode(
                        usuario = getData(USER),
                        password = getData(PASSWORD),
                        code = customDialogList.getValueTwo()
                    )
                    customDialogList.dismiss()
                }
                scanRequest()
                hideKeyboards()
            } else {
                getString(R.string.scanItemValidate).toast(requireContext())
            }


        }.setKoButton(getString(R.string.close)) {
            scanRequest()
            hideKeyboards()
            customDialogList.dismiss()
        }.setHintValue(getString(R.string.quantitySelect)).setValue(total).setHintValueTwo(getString(R.string.scanItem))
            .setValueTwo("").show()


        customDialogList.getEditTextTwo().post(Runnable {
            customDialogList.getEditTextTwo().requestFocusFromTouch()
            val lManager: InputMethodManager =
                requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            lManager.hideSoftInputFromWindow(
                customDialogList.getEditTextTwo().windowToken,
                InputMethodManager.SHOW_FORCED
            )
        })

        customDialogList.getEditTextTwo().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (customDialogList.getValueTwo().isNotEmpty()) {
                    if (checkItemScan(customDialogList.getValueTwo())) {
                        onQuantityOfShelvingSelected(itemShelvingFk)
                        mpok?.start()
                        customDialogList.dismiss()
                    } else {
                        itemShelvingFkStored = itemShelvingFk
                        binding.splashProgress.visibility = View.VISIBLE
                        viewModel.getIdFromCode(
                            usuario = getData(USER),
                            password = getData(PASSWORD),
                            code = customDialogList.getValueTwo()
                        )
                        customDialogList.dismiss()
                    }
                } else {
                    getString(R.string.scanItemValidate).toast(requireContext())
                }
                scanRequest()
                hideKeyboards()
                return@setOnEditorActionListener true

            }
            false
        }

        placementSupplyAdapter =
            BarcodeAdapter(listPlacementSupply, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {
                    placementSupplyListVO.list.forEach {
                        if (it.proposal == item.code) {
                            customDialogList.setValue(it.total)
                            total = it.total
                            itemShelvingFk = it.itemShelvingFk
                        }
                    }

                }
            }, showDelete = false)

        customDialogList.getRecyclerView().adapter = placementSupplyAdapter

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

    }

    private fun onQuantityOfShelvingSelected(itemShelvingFk: String) {
        //1 - MODIFICAR CANTIDAD DEL CARRO
        try {
            val shelvingVisible = sales[storedPosition].carros[storedShelvingPosition].stockTotal

            sales[storedPosition].carros[storedShelvingPosition].stockTotal =
                (shelvingVisible.toInt() - customDialogList.getValue().toInt()).toString()

            viewModel.itemShelvingPlacementSupplyAdd(
                usuario = getData(USER),
                password = getData(PASSWORD),
                itemShelvingFk = itemShelvingFk,
                itemPlacementSupplyFk = sales[storedPosition].id,
                quantity = customDialogList.getValue()
            )

        } catch (e: Exception) {
        }

        //2- MODIFICAR EL PICKED DEL SALE
        try {
            sales[storedPosition].saldo =
                sales[storedPosition].saldo - customDialogList.getValue().toInt()
        } catch (e: Exception) {
        }

        //3- MARCAR LINEA
        markLine(storedPosition)


    }


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

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconParking = ImageView(context)
        iconParking.setImageResource(R.drawable.ic_local_parking_black_24dp)


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconParking.tooltipText = getTooltip(R.drawable.ic_local_parking_black_24dp)
        }

        listIcons.add(iconParking)

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

                    when (item) {
                        iconParking.drawable -> pasillerosItemClickListener?.onPasillerosItemClickListener(
                            PasillerosItemVO(title = getString(R.string.Parking)),
                            ""
                        )
                    }

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


    private fun scanRequest() {
        binding.scanInput.requestFocus()
        hideKeyboards()
    }

    private fun checkItemScan(valueToCheck: String): Boolean {
        val saleToCheck = sales[storedPosition]
        return saleToCheck.itemFk == valueToCheck
    }

    private fun showErrorMessage(text: String) {
        customDialog.setTitle(getString(R.string.errorMarkLine)).setDescription(text)
            .setKoButton(getString(R.string.close)) {
                customDialog.dismiss()
            }.show()
    }

    private fun showScanner(index: Int, sale: PreSacadorItemVO) {
        customDialogInput.setTitle("" + sale.itemFk)
            .setDescription(getString(R.string.scanWagonForItem)).setOkButton(getString(R.string.accept)) {
            if (!customDialogInput.getValue().isNullOrEmpty()) {
                findSale(customDialogInput.getValue(), index)
            }
            customDialogInput.setValue("")
            scanRequest()
            customDialogInput.dismiss()
            hideKeyboards()
        }.setKoButton(getString(R.string.cancel)) {
            customDialogInput.dismiss()
        }.setValue("").show()
        customDialogInput.getEditText().requestFocus()
        customDialogInput.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (!customDialogInput.getValue().isNullOrEmpty()) {
                    findSale(customDialogInput.getValue(), index)
                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            false
        }

    }


    private fun unMarkLine(position: Int) {

        if (sales[position].quantity == sales[position].picked) {
            customDialog.setTitle(getString(R.string.unmarkLine))
                .setDescription(getString(R.string.goUnmark) + sales[position].itemFk + getString(R.string.sure))
                .setOkButton(getString(R.string.unmark)) {
                    sales[position].picked = 0
                    saleAdapter!!.notifyDataSetChanged()

                    /*viewModel.saleTrackingDel(
                        usuario = user,
                        password = password,
                        saleFk = sales[position].idMovimiento
                    )*/
                    scanRequest()
                    customDialog.dismiss()
                }.setKoButton(getString(R.string.cancel)) {
                scanRequest()
                customDialog.dismiss()
            }.show()
        }


    }

    private fun markLine(position: Int) {
        saleAdapter!!.notifyDataSetChanged()
    }


}
