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.text.InputType
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import es.verdnatura.R
import es.verdnatura.databinding.FragmentInventoryParkingBinding
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.*
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.InventoryParkingAdapter
import es.verdnatura.presentation.view.feature.inventario.model.ItemInventoryParking
import es.verdnatura.presentation.view.feature.inventario.model.ItemShelvingChecked
import es.verdnatura.presentation.view.feature.inventario.model.ItemShelvingVisible
import es.verdnatura.presentation.view.feature.inventario.model.ItemShelvingVisibleZero
import es.verdnatura.presentation.view.feature.ubicador.model.ItemUbicadorVO

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class InventaryParkingFragment(
    var title: String = "",
) : BaseFragment<FragmentInventoryParkingBinding, InventaryViewModel>(
    InventaryViewModel::class
) {
    private var adapter: InventoryParkingAdapter? = null
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogList: CustomDialogList
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var isBack = false
    private lateinit var myListInventory: MutableList<ItemInventoryParking>
    private var listParkings: ArrayList<BarcodeVO> = ArrayList()
    private var listWagonsAdapter: BarcodeAdapter? = null
    private var positionShelvingChecking: Int = -1
    private var positionItemChecking: Int = -1
    private var scrollPosition = 0
    private var parkingFrom = ""
    private var parkingTo = ""
    private var filterActivated = false
    private var shelvingSaved = ""
    val listIcons: ArrayList<ImageView> = ArrayList()

    companion object {
        fun newInstance(title: String) = InventaryParkingFragment(title)
    }

    override fun getLayoutId(): Int = R.layout.fragment_inventory_parking
    override fun onPause() {

        try {
            val layoutManager =
                binding.inventoryParkingRecyclerview.layoutManager as LinearLayoutManager
            scrollPosition = layoutManager.findFirstVisibleItemPosition()
        } catch (exception: Exception) {

        }

        isBack = true
        super.onPause()

    }

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

    @RequiresApi(Build.VERSION_CODES.O)
    override fun init() {

        customDialogInput = CustomDialogInput(requireContext())
        customDialogList = CustomDialogList(requireContext())

        ma.hideBottomNavigation(GONE)
        binding.mainToolbar.toolbarTitle.text = title
        setEvents()
        setViews()
        setToolBar()
        if (!isBack) {
            setParkingFromTo()
        }
        super.init()
    }

    private fun setViews() {
        binding.inventoryParkingRecyclerview.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                scrollPosition =
                    (recyclerView.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                super.onScrolled(recyclerView, dx, dy)
            }
        })
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setToolBar() {

        val iconAdd = ImageView(context)
        iconAdd.setImageResource(R.drawable.ic_add_black_24dp)

        val iconReload = ImageView(context)
        iconReload.setImageResource(R.drawable.ic_autorenew_black_24dp)

        val iconReset = ImageView(context)
        iconReset.setImageResource(R.drawable.ic_remove_checks)

        val iconFilter = ImageView(context)
        iconFilter.setImageResource(R.drawable.ic_filter_inventory)

        val iconParkingFrom = ImageView(context)
        iconParkingFrom.setImageResource(R.drawable.ic_eye_inventory)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconParkingFrom.tooltipText = getTooltip(R.drawable.ic_eye_inventory)
            iconReload.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)
            iconAdd.tooltipText = getString(R.string.addItemShelving)
            iconReset.tooltipText = getTooltip(R.drawable.ic_remove_checks)
            iconFilter.tooltipText = getTooltip(R.drawable.ic_filter_inventory)

        }

        if (listIcons.isEmpty()) {
            listIcons.add(iconParkingFrom)
            listIcons.add(iconFilter)
            listIcons.add(iconReset)
        } else {
            listIcons.clear()
            listIcons.add(iconParkingFrom)
            listIcons.add(iconFilter)
            listIcons.add(iconReset)
        }

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

                    when (item) {

                        iconFilter.drawable -> {
                            try {
                                filterActivated = !filterActivated
                                adapter!!.setItems(if (filterActivated) {
                                    myListInventory.filter { it.isChecked == null || it.isChecked == 0 }
                                } else {
                                    myListInventory
                                })
                                iconFilter.drawable.setTint(
                                    ContextCompat.getColor(
                                        context!!,
                                        if (filterActivated) R.color.verdnatura_pumpkin_orange else R.color.verdnatura_white
                                    )
                                )

                            } catch (ex: Exception) {
                            }

                        }

                        iconReset.drawable -> {
                            if (!myListInventory.isNullOrEmpty()) {
                                binding.textinputlayoutMatricula.visibility = VISIBLE
                                showResetShelving()
                            } else {
                                getString(R.string.listInventoryEmpty).toast(requireContext())
                            }

                        }

                        iconParkingFrom.drawable -> {

                            setParkingFromTo()
                        }

                    }
                }

            })
        chageListAdapter(listIcons.filter { it != iconReset })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun chageListAdapter(filterList: List<ImageView>, removeReset: Boolean = false) {
        if (!removeReset) {
            (binding.mainToolbar.toolbarIcons.adapter as ToolBarAdapterTooltip).setItemsList(
                filterList
            )
        } else {
            (binding.mainToolbar.toolbarIcons.adapter as ToolBarAdapterTooltip).setItemsList(
                filterList.filter {
                    it.drawable.constantState?.equals(
                        context?.getDrawable(
                            R.drawable.ic_remove_checks
                        )?.constantState
                    ) != true
                })
        }
    }

    private fun showResetShelving() {
        customDialogInput.setFocusText()
        customDialogInput.setInputText(InputType.TYPE_CLASS_TEXT)
        customDialogInput.setTitle(getString(R.string.checkItemShelvingDescrip))
            .setDescription(getString(R.string.checkItemShelvingSelect))
            .setOkButton(getString(R.string.cancel)) {
                customDialogInput.dismiss()
            }.setKoButton(getString(R.string.ok)) {
                checkSelvingsForUpdate(customDialogInput.getValue())
            }.show()

        customDialogInput.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                if (customDialogInput.getValue().isNotEmpty()) {
                    checkSelvingsForUpdate(customDialogInput.getValue())
                }
                return@setOnEditorActionListener true
            }
            false
        }

    }

    private fun checkSelvingsForUpdate(shelvingInput: String) {

        val filter = JsonObject()
        val inqValues = JsonArray()
        for (item in myListInventory) {
            if (item.shelvingFk == shelvingInput) {
                inqValues.add(item.id)
            }
        }
        if (inqValues.size() == 0) {
            ma.messageWithSound("", true, true, "", null)
        } else {
            filter.add("id", JsonObject().apply { add("inq", inqValues) })
            viewModel.itemShelvingsReset(
                filter, ItemShelvingChecked(null, mobileApplication.userId!!)
            )
        }
        ma.hideKeyboard(customDialogInput.getEditText())
        customDialogInput.setValue("")
        customDialogInput.dismiss()
        binding.editMatricula.requestFocus()

    }

    private fun setParkingFromTo() {
        binding.textinputlayoutMatricula.visibility = VISIBLE
        customDialogList.setTitle(getString(R.string.selectParkingsCheckin))
        customDialogList.setDescription(getString(R.string.selectParkingsFrom))
            .setKoButton(getString(R.string.cancel)) {
                ma.hideKeyboard(customDialogList.getEditText())
                listParkings = 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 {

                        if (listParkings.size == 1) {
                            callGetInventory(
                                listParkings.first().code!!.uppercase(),
                                customDialogList.getValue().uppercase()
                            )

                            ma.hideKeyboard(customDialogList.getEditText())
                            listParkings.clear()
                            customDialogList.dismiss()
                            binding.editMatricula.requestFocus()
                        } else {
                            customDialogList.setDescription(getString(R.string.selectParkingsTo))
                            listParkings.add(0, BarcodeVO(code = customDialogList.getValue()))
                        }

                    } catch (e: Exception) {
                        ma.messageWithSound(e.message.toString(), true, true, "", true)
                    }

                    listWagonsAdapter!!.notifyItemInserted(listParkings.size - 1)
                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }

        listWagonsAdapter = BarcodeAdapter(
            listParkings, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {

                }
            }, showDelete = false
        )
        customDialogList.getRecyclerView().adapter = listWagonsAdapter

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

    }

    private fun callGetInventory(parkingFromScan: String, parkingToScan: String) {
        parkingFrom = parkingFromScan
        parkingTo = parkingToScan
        viewModel.getInventoryParking(
            parkingFromScan, parkingToScan
        )
        binding.mainToolbar.toolbarTitle.text = "$parkingFrom → $parkingTo"
    }

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("SetTextI18n")
    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            isBack = true
            if (shelvingSaved.isNullOrBlank()) {
                requireActivity().onBackPressed()
            } else {
                resetChecking()

            }
        }

        binding.inventorySwipe.setOnRefreshListener {

            positionShelvingChecking = -1
            positionItemChecking = -1
            shelvingSaved = ""
            viewModel.getInventoryParking(
                parkingFrom, parkingTo
            )

            binding.editMatricula.hint = getString(R.string.scanShelving)
            chageListAdapter(listIcons.filter {
                it.drawable.constantState?.equals(
                    context?.getDrawable(
                        R.drawable.ic_remove_checks
                    )?.constantState
                ) != true
            })

            binding.inventorySwipe.isRefreshing = false

        }
        binding.editMatricula.requestFocus()
        binding.editMatricula.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                if (!binding.editMatricula.text.toString().isEmpty()) {

                    if (positionShelvingChecking == -1) {

                        try {
                            binding.editMatricula.setText(
                                itemScanValue(
                                    binding.editMatricula.text.toString(), "buy", "more"
                                ).toString().uppercase()
                            )
                        } catch (ex: Exception) {
                            ex.message!!.toast(requireContext())

                        }

                        positionShelvingChecking = myListInventory.indexOfFirst { item ->
                            item.shelvingFk.uppercase() == binding.editMatricula.text.toString()
                        }
                        if (positionShelvingChecking != -1) {
                            shelvingSaved = myListInventory[positionShelvingChecking].shelvingFk.uppercase()
                        }

                        var allChecked = if (positionShelvingChecking != -1) {
                            myListInventory.filter { it.shelvingFk.uppercase() == myListInventory[positionShelvingChecking].shelvingFk.uppercase() }
                                .all { item ->
                                    item.isChecked != null && item.isChecked!! > 0
                                }
                        } else {
                            false
                        }

                        if (allChecked) {
                            ma.messageWithSound(
                                getString(R.string.plateChecked), false, true, "", isToasted = true
                            )
                            chageListAdapter(listIcons)
                            adapter!!.setItems(myListInventory.filter { it.shelvingFk.uppercase() == myListInventory[positionShelvingChecking].shelvingFk.uppercase() })
                            positionShelvingChecking = -1
                            positionItemChecking = -1
                            shelvingSaved = ""
                            binding.editMatricula.hint = getString(R.string.scanShelving)
                            binding.textinputlayoutMatricula.hint = getString(R.string.scanShelving)

                        } else {

                            if (positionShelvingChecking == -1) {
                                ma.messageWithSound(
                                    getString(R.string.shelvingNotFound), true, true, "", true
                                )
                            } else {

                                chageListAdapter(listIcons)
                                adapter!!.setItems(myListInventory.filter { it.shelvingFk == myListInventory[positionShelvingChecking].shelvingFk })

                                binding.editMatricula.hint = getString(R.string.scanItemForChecking)
                                binding.textinputlayoutMatricula.hint =
                                    getString(R.string.scanItemForChecking)

                            }
                        }
                    } else {

                        try {

                            viewModel.getIdFromCodeSalix(
                                code = itemScanValue(
                                    binding.editMatricula.text.toString(), "buy", "more"
                                ).toString()
                            )

                        } catch (ex: Exception) {
                            ma.messageWithSound(ex.message!!, true, true, "", null)
                        }

                    }
                    binding.editMatricula.setText("")
                    ma.hideKeyboard(binding.editMatricula)
                }
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

    }

    private fun resetChecking() {
        chageListAdapter(listIcons)
        positionShelvingChecking = -1
        positionItemChecking = -1
        shelvingSaved = ""
        binding.editMatricula.hint = getString(R.string.scanShelving)
        binding.textinputlayoutMatricula.hint = getString(R.string.scanShelving)
        callGetInventory(parkingFrom, parkingTo)
    }

    private fun checkItem(itemCode: String) {
        positionItemChecking = myListInventory.indexOfFirst { item ->
            item.itemFk == itemCode.toInt() && item.shelvingFk.uppercase() == myListInventory[positionShelvingChecking].shelvingFk.uppercase() && item.isChecked == null
        }


        if (positionItemChecking == -1) {
            ma.messageWithSound(
                getString(R.string.itemNotFoundScanAgain), true, true, "", true
            )

            positionShelvingChecking = -1
            binding.editMatricula.hint = getString(R.string.scanShelvingAgain)
        } else {

            try {
                viewModel.itemShelvingUpdate(
                    myListInventory[positionItemChecking].id,
                    ItemShelvingChecked(true, mobileApplication.userId!!)
                )
                myListInventory[positionItemChecking].isChecked = 1
                adapter!!.notifyDataSetChanged()
                binding.editMatricula.hint = getString(R.string.scanShelving)

                var allChecked =
                    myListInventory.filter { it.shelvingFk.uppercase() == myListInventory[positionShelvingChecking].shelvingFk.uppercase() }
                        .all { item ->
                            item.isChecked != null && item.isChecked!! > 0
                        }
                if (allChecked) {
                    shelvingSaved = ""
                }
                positionItemChecking = -1
                positionShelvingChecking = -1

            } catch (ex: Exception) {

            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun observeViewModel() {

        with(viewModel) {

            inventoryListParking.observe(viewLifecycleOwner, Observer {

                if (it.list.isNotEmpty()) {
                    if (it.list[0].isError) {
                        ma.messageWithSound(
                            it.list[0].errorMessage, it.list[0].isError, false
                        )

                    } else {
                        myListInventory = it.list as MutableList<ItemInventoryParking>
                        createListInventoryParking()
                        customDialogInput.dismiss()
                        binding.textinputlayoutMatricula.visibility = VISIBLE
                        binding.editMatricula.requestFocus()

                    }
                }
            })

            loadReponseCode.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    checkItem(it.response)
                }
            }

            response.observe(viewLifecycleOwner, Observer {
                chageListAdapter(listIcons, true)
                callGetInventory(
                    parkingFrom, parkingTo
                )

            })
            responseReset.observe(viewLifecycleOwner, Observer {
                callGetInventory(
                    parkingFrom, parkingTo
                )
                chageListAdapter(listIcons, true)
            })
        }

    }

    private fun createListInventoryParking(
    ) {

        adapter = InventoryParkingAdapter((if (filterActivated) {
            if (!shelvingSaved.isNullOrEmpty()) {
                myListInventory.filter { (it.isChecked == null || it.isChecked == 0) && it.shelvingFk.uppercase() == shelvingSaved.uppercase() }
            } else {
                myListInventory.filter { it.isChecked == null || it.isChecked == 0 }
            }

        } else {
            if (!shelvingSaved.isNullOrEmpty()) {
                myListInventory.filter { it.shelvingFk.uppercase() == shelvingSaved.uppercase() }
            } else {
                myListInventory
            }
        }),
            onPasillerosItemClickListener = pasillerosItemClickListener!!,
            onVisibleInventoryClickListener = object : OnVisibleInventoryClickListener {
                override fun onVisibleInventoryClickListener(item: ItemInventoryParking) {
                    changeVisible(item)
                }

            },
            onMoreClickListener = object : OnMoreClickListener {
                override fun onMoreClickListener(item: ItemUbicadorVO) {
                }

            })


        binding.inventoryParkingRecyclerview.adapter = adapter
        binding.inventoryParkingRecyclerview.layoutManager = LinearLayoutManager(
            requireContext(), LinearLayoutManager.VERTICAL, false
        )

    }

    private fun changeVisible(item: ItemInventoryParking) {

        customDialogInput.setInputText(InputType.TYPE_CLASS_NUMBER)
        customDialogInput.setTitle(getString(R.string.quantity))
        customDialogInput.setDescription(getString(R.string.quantityVisible)).setValue("")
            .setOkButton(getString(R.string.modify)) {
                try {
                    if (customDialogInput.getValue().toInt() >= 0) {
                        viewModel.itemShelvingUpdate(
                            item.id, if (customDialogInput.getValue().toInt() == 0) {
                                ItemShelvingVisibleZero(customDialogInput.getValue().toInt(), true)
                            } else {
                                ItemShelvingVisible(customDialogInput.getValue().toInt())
                            }
                        )

                    } else {
                        throw Exception("")
                    }
                } catch (err: Exception) {
                    (getString(R.string.errorQuantity).toast(requireContext()))
                }
                customDialogInput.setValue("")
                customDialogInput.dismiss()

            }.setKoButton(getString(R.string.cancel)) {
                customDialogInput.dismiss()
            }.show()
        customDialogInput.setFocusText()
    }

}