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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentInventaryBinding
import es.verdnatura.domain.ConstAndValues.BUYER
import es.verdnatura.domain.ConstAndValues.BUYERID
import es.verdnatura.domain.ConstAndValues.WAREHOUSEFK
import es.verdnatura.domain.toast
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.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogTwoButtons
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 es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import ir.mirrajabi.searchdialog.SimpleSearchDialogCompat
import kotlinx.coroutines.launch

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

    private var adapter: InventoryAdapter? = null
    private lateinit var customDialogInput: CustomDialogInput
    private var listInventory: ArrayList<ItemInventaryVO> = ArrayList()
    private var listInventoryAux: ArrayList<ItemInventaryVO> = ArrayList()
    private lateinit var customDialog: CustomDialogTwoButtons
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var layoutManager: LinearLayoutManager? = null
    private var firstVisiblePosition = 0
    private var secondVisiblePosition = 1
    private lateinit var itemClicked: ItemInventaryVO
    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() {

        viewModel.itemShelvingBuyerGet()
        binding.filterBuyer.text = mobileApplication.dataStoreApp.readDataStoreKey<String>((BUYER))
        buyerId = mobileApplication.dataStoreApp.readDataStoreKey((BUYERID))
        if (buyerId.isNotBlank()) {
            viewModel.getInventory(
                buyerId.toInt(), mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
            )
        }
        binding.filterBuyer.setOnClickListener {
            SimpleSearchDialogCompat(
                context,
                getString(R.string.compradores),
                getString(R.string.escribirparteNombre),
                null,
                items
            ) { baseSearchDialogCompat, nombre, position ->

                binding.filterBuyer.text = (nombre.title)
                buyerId = nombre.getBuyerId()

                lifecycleScope.launch {
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        BUYER, nombre.getBuyerNickname()
                    )
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        BUYERID, nombre.getBuyerId()
                    )
                }
                viewModel.getInventory(
                    nombre.getBuyerId().toInt(),
                    mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
                )
                baseSearchDialogCompat.dismiss()
            }.show()
        }
        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialogTwoButtons(requireContext())
        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)
        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) {

                        firstVisiblePosition = layoutManager?.findFirstVisibleItemPosition() ?: 0
                        if (buyerId.isNotBlank()) {
                            viewModel.getInventory(
                                buyerId.toInt(),
                                mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
                            )
                        } else {
                            ma.messageWithSound(
                                getString(R.string.selectBuyer),
                                true,
                                isPlayed = true,
                                isToasted = true
                            )
                        }

                    }

                }

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

    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }
        binding.filterItemFk.setOnKeyListener { v, keyCode, event ->
            if (binding.filterItemFk.text.toString().isEmpty()) {

                if (listInventory.size != listInventoryAux.size) {
                    listInventory.removeAll(listInventoryAux.toSet())
                    listInventory.addAll(listInventoryAux)

                }

            } else {

                setFilterItem()

            }
            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 <= listInventory.size) {
                binding.locationRecyclerview.layoutManager!!.scrollToPosition(firstVisiblePosition)
            }
        }
    }

    override fun observeViewModel() {
        with(viewModel) {
            buyersList.observe(viewLifecycleOwner) {
                createBuyerList(it.list)
            }

            inventaryList.observe(viewLifecycleOwner) { it ->
                listInventory = ArrayList()
                listInventoryAux = ArrayList()
                it.list.forEach {
                    if (it.nicho != 0) {
                        listInventory.add(it)
                        listInventoryAux.add(it)
                    }
                }
                adapter = InventoryAdapter(listInventory, object : OnInvetoryNichoClickListener {
                    override fun onInvetoryNichoClickListener(item: ItemInventaryVO) {
                        customDialog.setTitle(item.itemFk.toString() + "\n" + item.longName)
                            .setDescription(getString(R.string.quantityReal) + item.nicho + ")")
                            .setOkButton(getString(R.string.pull)) {
                                //Tarea 7161
                                viewModel.itemSetVisibleDiscard(
                                    item.itemFk!!.toInt(),
                                    mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK),
                                    item.nicho!!
                                )
                                itemClicked = item
                                customDialog.dismiss()
                            }.setOkButtonTwo(getString(R.string.titleUbicator)) {
                                customDialog.dismiss()
                                ma.onPasillerosItemClickListener(
                                    PasillerosItemVO(
                                        title = R.string.titleUbicator,
                                    ), entryPoint = ""
                                )

                            }.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 <= listInventory.size) {
                    binding.locationRecyclerview.layoutManager!!.scrollToPosition(
                        firstVisiblePosition
                    )
                }
                if (binding.filterItemFk.text!!.isNotEmpty()) {
                    setFilterItem()

                }
            }

            response.observe(viewLifecycleOwner) {
                changeOfflineValue(itemClicked)
            }
        }
    }

    private fun setFilterItem() {
        listInventory.removeAll(listInventoryAux.toSet())

        listInventory.addAll(listInventoryAux.filter {
            it.itemFk!!.toString().contains(
                binding.filterItemFk.text.toString(), true
            ) || it.producer?.contains(
                binding.filterItemFk.text.toString(), true
            ) == true || it.longName?.contains(
                binding.filterItemFk.text.toString(), ignoreCase = true
            ) == true
        })
    }

    private fun changeOfflineValue(item: ItemInventaryVO) {
        try {
            listInventory.removeAt(listInventory.indexOf(item))
            listInventoryAux.removeAt(listInventoryAux.indexOf(item))
        } catch (ex: Exception) {
            ex.message!!.toast(requireContext())
        }
        adapter?.notifyItemRemoved(listInventory.indexOf(item))

    }

    private fun createBuyerList(list: List<BuyerVO>) {
        items.clear()
        if (list.isNotEmpty()) list.forEach { buyer ->
            items.add(SearchBuyerModel(buyer.nickname, buyer.userFk))
        }
    }

}


