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

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentFaltasBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.feature.faltas.adapter.FaltasAdapter
import es.verdnatura.presentation.view.feature.faltas.model.ItemFaltasVO


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class FaltasFragment :
    BaseFragment<FragmentFaltasBinding, FaltasViewModel>(FaltasViewModel::class) {

    private var adapter: FaltasAdapter? = null
    private lateinit var customDialogInput: CustomDialogInput
    private var listInvetory: ArrayList<ItemFaltasVO> = ArrayList()
    private var listInvetoryAux: ArrayList<ItemFaltasVO> = ArrayList()

    // private lateinit var customDialog: CustomDialog
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var reload = false
    private var hideLoad = true

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

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

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

    override fun onCreate(savedInstanceState: Bundle?) {

        viewModel.getFaltas(getData(USER), getData(PASSWORD), getData(WAREHOUSEFK))
        super.onCreate(savedInstanceState)
    }

    override fun init() {
        binding.splashProgress.visibility = View.VISIBLE
        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text = getString(R.string.faultsReview)
        setToolBar()

        customDialogInput = CustomDialogInput(requireContext())
        // customDialog = CustomDialog(requireContext())
        setEvents()
        if (reload) {
            reload = false
            hideLoad = false
            binding.splashProgress.visibility = View.VISIBLE
            viewModel.getFaltas(getData(USER), getData(PASSWORD), getData(WAREHOUSEFK))
        }
        super.init()
    }


    private fun setToolBar() {

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconReload = ImageView(context)
        iconReload.setImageResource(R.drawable.ic_autorenew_black_24dp)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconReload.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)

        }
        listIcons.add(iconReload)
        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    if (item == iconReload.drawable) {
                        binding.splashProgress.visibility = View.VISIBLE
                        viewModel.getFaltas(getData(USER), getData(PASSWORD), getData(WAREHOUSEFK))
                    }
                }

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

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

        binding.filterItemFk.setOnKeyListener { v, keyCode, event ->
            if (binding.filterItemFk.text.toString().isNullOrEmpty()) {
                if (listInvetory.size != listInvetoryAux.size) {
                    listInvetory.removeAll(listInvetoryAux)
                    listInvetoryAux.forEach {
                        listInvetory.add(it)
                    }

                }

            } else {
                listInvetory.removeAll(listInvetoryAux)
                listInvetoryAux.forEach {
                    if (it.itemFk.contains(binding.filterItemFk.text.toString(), true)) {
                        listInvetory.add(it)
                    }
                }


            }
            adapter!!.notifyDataSetChanged()
            return@setOnKeyListener false
        }
    }

    override fun observeViewModel() {
        with(viewModel) {
            faltasList.observe(viewLifecycleOwner, Observer {
                if (hideLoad) {
                    binding.splashProgress.visibility = View.GONE
                } else {
                    hideLoad = true
                }
                listInvetory = ArrayList()
                listInvetoryAux = ArrayList()
                it.list.forEach {
                    listInvetory.add(it)
                    listInvetoryAux.add(it)
                }

                adapter = FaltasAdapter(listInvetory, object : OnFaltasNichoClickListener {
                    override fun onFaltasNichoClickListener(item: ItemFaltasVO) {
                        customDialogInput.setTitle(item.itemFk + "\n" + item.longName + " " + item.size)
                            .setDescription(getString(R.string.quantityReal) + item.nicho + ")")
                            .setOkButton(getString(R.string.pull)) {
                                viewModel.itemStockUpdate(
                                    item.itemFk,
                                    getData(WAREHOUSEFK),
                                    getData(USER),
                                    getData(PASSWORD),
                                    customDialogInput.getValue(),
                                    "0"

                                )
                                changeOfflineValue(item)
                                customDialogInput.dismiss()
                            }.setKoButton(getString(R.string.cancel)) {
                            customDialogInput.dismiss()
                        }.setValue("0").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()) {
                                        viewModel.itemStockUpdate(
                                            item.itemFk,
                                            getData(WAREHOUSEFK),
                                            getData(USER),
                                            getData(PASSWORD),
                                            customDialogInput.getValue(),
                                            "0"

                                        )
                                        changeOfflineValue(item)
                                    }
                                    customDialogInput.setValue("")
                                    customDialogInput.dismiss()
                                    ma.hideKeyboard(customDialogInput.getEditText())
                                    return@setOnEditorActionListener true
                                }
                                false
                            }

                    }
                }, object : OnFaltasReviewClickListener {
                    override fun onFaltasReviewClickListener(item: ItemFaltasVO) {
                        viewModel.faultsReview_isChecked(
                            getData(USER),
                            getData(PASSWORD),
                            item.itemFk,
                            getData(WAREHOUSEFK)
                        )
                        changeOfflineValue(item)
                    }

                }, pasillerosItemClickListener!!)
                binding.locationRecyclerview.adapter = adapter
                binding.locationRecyclerview.layoutManager =
                    LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

            })


            response.observe(viewLifecycleOwner, Observer {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, false)
                }
            })
        }
    }

    private fun changeOfflineValue(item: ItemFaltasVO) {
        var i = 0
        var position = 0
        listInvetory.forEach {
            if (it.itemFk == item.itemFk) {
                position = i
            }
            i = i.plus(1)
        }
        listInvetory.removeAt(position)

        i = 0
        position = 0
        listInvetoryAux.forEach {
            if (it.itemFk == item.itemFk) {
                position = i
            }
            i = i.plus(1)
        }
        listInvetoryAux.removeAt(position)
        adapter?.notifyDataSetChanged()

        reload = true

    }


}
