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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentGeneralBlackBinding
import es.verdnatura.domain.ConstAndValues
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.OnCollectionTicketSelectedListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
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.inventario.adapter.InventoryParkingAdapter
import es.verdnatura.presentation.view.feature.inventario.model.ItemInventoryParking
import es.verdnatura.presentation.view.feature.sacador.model.CollectionTicket
import kotlinx.coroutines.runBlocking

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class PickerHelperFragment(
    var title: String = ""
) : BaseFragment<FragmentGeneralBlackBinding, SacadorViewModel>(
    SacadorViewModel::class
) {
    private var onCollectionSelectedListener: OnCollectionTicketSelectedListener? = null
    private var adapter: InventoryParkingAdapter? = null
    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) = PickerHelperFragment(title)
    }

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

        isBack = true
        super.onPause()

    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnCollectionTicketSelectedListener) onCollectionSelectedListener = context
    }

    override fun init() {

        customDialogList = CustomDialogList(requireContext())
        ma.hideBottomNavigation(GONE)
        binding.mainToolbar.toolbarTitle.text = title
        setEvents()
        setToolBar()
        checkParkingsToPicker()

        super.init()
    }

    private fun checkParkingsToPicker() {

        val parkingFrom = mobileApplication.dataStoreApp.readDataStoreKey<String>("PARKING_FROM")
        val parkingTo = mobileApplication.dataStoreApp.readDataStoreKey<String>("PARKING_TO")

        if (parkingTo.isNotBlank()) {
            binding.mainToolbar.toolbarTitle.text =
                getString(R.string.parkingForPicking, parkingFrom, parkingTo)
        } else {
            showSettingsHelper(

            )
        }

    }

    private fun setToolBar() {
        val listIcons: ArrayList<ImageView> = ArrayList()

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

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

        iconParkingFrom.tooltipText = getString(R.string.editParking)
        iconReset.tooltipText = getString(R.string.resetParking)

        listIcons.add(iconReset)
        listIcons.add(iconParkingFrom)

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

                    when (item) {

                        iconReset.drawable -> {

                            resetParkings()

                        }

                        iconParkingFrom.drawable -> {

                            showSettingsHelper()
                        }

                    }
                }

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

    private fun resetParkings() {
        binding.mainToolbar.toolbarTitle.text = title
        runBlocking {
            mobileApplication.dataStoreApp.editDataStoreKey(
                "PARKING_FROM", ""
            )
            mobileApplication.dataStoreApp.editDataStoreKey(
                "PICKING_FROM", 0
            )
            mobileApplication.dataStoreApp.editDataStoreKey(
                "PARKING_TO", ""
            )
            mobileApplication.dataStoreApp.editDataStoreKey(
                "PICKING_TO", 0
            )
        }
        showSettingsHelper()
    }

    private fun showSettingsHelper() {

        customDialogList.setTitle(
            "Parkings del almacén"
        )
        customDialogList.setDescription(

            "Escanea parkings de los pasillos"
        ).setKoButton(getString(R.string.cancel)) {
                ma.hideKeyboard(customDialogList.getEditText())
                listParkings = ArrayList()
                customDialogList.dismiss()
                ma.onMyBackPressed()
            }.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 {

                        when (listParkings.size) {
                            0 -> {
                                listParkings.add(0, BarcodeVO(code = customDialogList.getValue()))
                                viewModel.getPickingOrder(customDialogList.getValue())

                            }

                            1 -> {
                                listParkings.add(
                                    0, BarcodeVO(code = customDialogList.getValue())
                                )
                                viewModel.getPickingOrder(customDialogList.getValue())

                            }

                            else -> {
                                listParkings.clear()
                                customDialogList.dismiss()

                            }

                        }

                    } catch (e: Exception) {
                        ma.messageWithSound(e.message.toString(), isError = true, isPlayed = true)
                    }

                    listWagonsAdapter!!.notifyItemChanged(0)
                }
                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)

    }

    @SuppressLint("SetTextI18n")
    private fun setEvents() {

        binding.scanInput.visibility = VISIBLE
        binding.scanInput.setHint(getString(R.string.scanCollection))
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        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().isNotEmpty()) {

                    try {
                        navigateToCollectionList(binding.scanInput.text.toString().toInt())

                    } catch (ex: Exception) {
                        ex.message!!.toast(requireContext())

                    }


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

    }

    private fun navigateToCollectionList(collectionFk: Int) {
        onCollectionSelectedListener!!.onCollectionSelected(
            CollectionTicket(collectionFk = collectionFk), ConstAndValues.PREPARED, true
        )
    }

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

        with(viewModel) {

            loadPickingOrder.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

                    if (!it.isError && it.response.isNotBlank()) {

                        runBlocking {
                            when (listParkings.size) {
                                1 -> {
                                    mobileApplication.dataStoreApp.editDataStoreKey(
                                        "PARKING_FROM", listParkings.first().code.toString()
                                    )
                                    mobileApplication.dataStoreApp.editDataStoreKey(
                                        "PICKING_FROM", it.response.toInt()
                                    )
                                }

                                2 -> {
                                    mobileApplication.dataStoreApp.editDataStoreKey(
                                        "PARKING_TO", listParkings.first().code.toString()
                                    )
                                    mobileApplication.dataStoreApp.editDataStoreKey(
                                        "PICKING_TO", it.response.toInt()
                                    )
                                    binding.mainToolbar.toolbarTitle.text = getString(
                                        R.string.parkingForPicking,
                                        listParkings[1].code,
                                        listParkings[0].code
                                    )
                                    listParkings.clear()
                                    customDialogList.dismiss()

                                }

                                else -> {
                                    //listParkings.clear()
                                    // customDialogList.dismiss()
                                    //  showSettingsHelper()
                                    ma.messageWithSound(
                                        "Parking no encontrado", isError = true, isPlayed = true
                                    )
                                }
                            }
                        }

                    }
                }
            }
        }
    }
}