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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentInventaryBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnInvetoryNichoClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.feature.calidad.model.BuyerVO
import es.verdnatura.presentation.view.feature.inventario.adapter.InventoryAdapter
import es.verdnatura.presentation.view.feature.inventario.model.ItemInventaryVO
import ir.mirrajabi.searchdialog.SimpleSearchDialogCompat
import ir.mirrajabi.searchdialog.core.SearchResultListener

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class InventaryFragment :
    BaseFragment<FragmentInventaryBinding, InventaryViewModel>(InventaryViewModel::class) {


    private var adapter: InventoryAdapter? = null
    private lateinit var customDialogInput: CustomDialogInput
    private var listInvetory: ArrayList<ItemInventaryVO> = ArrayList()
    private var listInvetoryAux: ArrayList<ItemInventaryVO> = ArrayList()
    private lateinit var customDialog: CustomDialog
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null

    // private var reload = false
    // private var hideLoad = true
    private var layoutManager: LinearLayoutManager? = null
    private var firstVisiblePosition = 0
    private var secondVisiblePosition = 1
    private lateinit var itemClicked: ItemInventaryVO


    //sergio : cmbios para insertar lista compradores en inventary en el searchable
    private val items = ArrayList<SearchBuyerModel>()
    private lateinit var buyerId: String


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

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

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


    override fun init() {

        binding.splashProgress.visibility = View.VISIBLE
        viewModel.itemShelvingBuyerGet(user = getData(USER), password = getData(PASSWORD))

        binding.filterBuyer.text = getData(BUYER)
        buyerId = getData(BUYERID)
        if (!buyerId.isBlank()) {
            binding.splashProgress.visibility = View.VISIBLE
            viewModel.getInventory(getData(USER), getData(PASSWORD), buyerId, getData(WAREHOUSEFK))
        }
        binding.filterBuyer.setOnClickListener {
            //SimpleSearchDialogCompat(context,getString(R.string.compradores),getString(R.string.escribirparteNombre),null,initData(),
            SimpleSearchDialogCompat(context,
                getString(R.string.compradores),
                getString(R.string.escribirparteNombre),
                null,
                items,
                SearchResultListener { baseSearchDialogCompat, nombre, position ->

                    binding.filterBuyer.text = (nombre.title)
                    saveBuyer(nombre.getBuyerNickname())
                    saveBuyerId(nombre.getBuyerId())
                    buyerId = nombre.getBuyerId()
                    viewModel.getInventory(
                        getData(USER),
                        getData(PASSWORD),
                        nombre.getBuyerId(),
                        getData(WAREHOUSEFK)
                    )
                    binding.splashProgress.visibility = View.VISIBLE
                    baseSearchDialogCompat.dismiss()
                }).show()
        }


        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())

        binding.splashProgress.visibility = View.VISIBLE
        binding.mainToolbar.toolbarTitle.text = getString(R.string.itemShelvingRadar)
        setToolBar()
        setEvents()
        super.init()
    }


    private fun setToolBar() {

        ma.hideBottomNavigation(View.GONE)

        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
                        firstVisiblePosition = layoutManager?.findFirstVisibleItemPosition() ?: 0
                        viewModel.getInventory(
                            getData(USER),
                            getData(PASSWORD),
                            buyerId,
                            getData(WAREHOUSEFK)
                        )

                    }

                }

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

    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        binding.filterItemFk.setOnKeyListener { v, keyCode, event ->
            if (binding.filterItemFk.text.toString().isEmpty()) {

                if (listInvetory.size != listInvetoryAux.size) {
                    listInvetory.removeAll(listInvetoryAux)
                    listInvetory.addAll(listInvetoryAux)

                }

            } else {

                listInvetory.removeAll(listInvetoryAux)
                listInvetory.addAll(listInvetoryAux.filter {
                    it.itemFk.contains(
                        binding.filterItemFk.text.toString(),
                        true
                    ) || it.producer.contains(
                        binding.filterItemFk.text.toString(),
                        true
                    ) || it.longName.contains(binding.filterItemFk.text.toString(),ignoreCase = true)
                })

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

    override fun onPause() {
        super.onPause()
        firstVisiblePosition = layoutManager?.findFirstVisibleItemPosition() ?: 0
    }

    override fun onResume() {
        super.onResume()
        if (binding.locationRecyclerview.layoutManager != null) {
            if (firstVisiblePosition <= listInvetory.size) {
                binding.locationRecyclerview.layoutManager!!.scrollToPosition(firstVisiblePosition)
            }
        }
    }

    override fun observeViewModel() {
        with(viewModel) {

            //sergio: para compradores
            buyersList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                createBuyerList(it.list)
            })


            inventaryList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                listInvetory = ArrayList()
                listInvetoryAux = ArrayList()
                it.list.forEach {
                    if (it.nicho != "0") {
                        listInvetory.add(it)
                        listInvetoryAux.add(it)
                    }
                }

                adapter = InventoryAdapter(listInvetory, object : OnInvetoryNichoClickListener {
                    override fun onInvetoryNichoClickListener(item: ItemInventaryVO) {

                        customDialog.setTitle(item.itemFk + "\n" + item.longName + " " + item.size)
                            .setDescription(getString(R.string.quantityReal) + item.nicho + ")")
                            .setOkButton(getString(R.string.pull)) {
                                binding.splashProgress.visibility = View.VISIBLE
                                viewModel.itemTrash(
                                    item.itemFk,
                                    getData(WAREHOUSEFK),
                                    getData(USER),
                                    getData(PASSWORD),
                                    item.nicho,
                                    "0"
                                )
                                itemClicked = item
                                customDialog.dismiss()
                            }.setKoButton(getString(R.string.cancel)) {

                                customDialog.dismiss()
                            }.show()

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

                if (firstVisiblePosition <= listInvetory.size) {
                    binding.locationRecyclerview.layoutManager!!.scrollToPosition(
                        firstVisiblePosition
                    )
                }


            })


            response.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, true)

                } else {
                    changeOfflineValue(itemClicked)
                }
            })
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    private fun changeOfflineValue(item: ItemInventaryVO) {
        listInvetory.removeAt(listInvetory.indexOf(item))
        listInvetoryAux.removeAt(listInvetoryAux.indexOf(item))
        listInvetory.filter { it.itemFk.contains("996") }
        adapter?.notifyDataSetChanged()
        //reload = true

    }


    //sergio:añadido para compradores
    private fun createBuyerList(list: List<BuyerVO>) {
        items.clear()
        list.forEach { buyer ->
            if (!buyer.isError) {
                try {
                    items.add(SearchBuyerModel(buyer.nickname, buyer.userFk))
                } catch (e: Exception) {
                }
            }
        }
    }


}


