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

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentItemshelvinglogBinding
import es.verdnatura.domain.ConstAndValues.LIMITRECORDSSHELVINGLOG
import es.verdnatura.domain.toLong
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.historicoshelving.adapter.ItemShelvingLogAdapter

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ItemShelvingLogFragment(
    var entryPoint: String = ""
) : BaseFragment<FragmentItemshelvinglogBinding, ItemShelvingLogViewModel>(ItemShelvingLogViewModel::class) {

    private var adapter: ItemShelvingLogAdapter? = null
    private var itemScan = ""
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var records: Int = LIMITRECORDSSHELVINGLOG
    private var shelving: String = ""
    private var positionScroll = 0
    private var positionToReturn = 0

    companion object {
        fun newInstance(entryPoint: String) = ItemShelvingLogFragment(entryPoint)
    }

    private lateinit var customDialog: CustomDialog

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

    override fun init() {

        customDialog = CustomDialog(requireContext())
        setEvents()
        setToolBar(getString(R.string.itemShelvingLog))
        setAdapter()
        super.init()

    }

    private fun setAdapter() {
        binding.itemshelvinglogRecyclerview.layoutManager =
            LinearLayoutManager(
                requireContext(),
                LinearLayoutManager.VERTICAL,
                false
            )
        adapter = ItemShelvingLogAdapter(
            listOf(),
            onPasillerosItemClickListener = pasillerosItemClickListener!!
        )
        binding.itemshelvinglogRecyclerview.adapter = adapter
    }

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

    private fun setToolBar(title: String) {
        binding.mainToolbar.toolbarTitle.text = title
    }

    private fun setEvents() {
        val scrollView = binding.scrollView
        scrollView.setOnScrollChangeListener { _, _, scrollY, _, _->
            positionScroll = scrollY
        }


        binding.scanInput.requestFocus()
        binding.loadMoreButton.setOnClickListener {
            positionToReturn = positionScroll
            records += LIMITRECORDSSHELVINGLOG
            try {
                viewModel.getIdFromCodeSalix(shelving.toLong().toString(), records)
            } catch (ex: Exception) {

                viewModel.itemShelvingLogGet(
                    shelving,
                    records
                )
            }
        }
        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()) {
                    //Tarea 7168
                    shelving = binding.scanInput.text.toString()
                    records = LIMITRECORDSSHELVINGLOG
                    try {
                        viewModel.getIdFromCodeSalix(binding.scanInput.toLong().toString(), records)
                    } catch (ex: Exception) {
                        viewModel.itemShelvingLogGet(
                            shelving,
                            records
                        )
                    }
                }
                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

    }

    override fun observeViewModel() {
        with(viewModel) {

            itemShelvingLogList.observe(viewLifecycleOwner) {

                if (it.list.isEmpty()) {
                    customDialog.setTitle(getString(R.string.noResults))
                        .setDescription(getString(R.string.noDataLabelScanned))
                        .setOkButton(getString(R.string.close)) {
                            customDialog.dismiss()
                        }.show()
                } else {

                    //TAREA 7168
                    if (it.list.size == records) {
                        binding.loadMoreButton.visibility = View.VISIBLE
                    } else {
                        binding.loadMoreButton.visibility = View.GONE
                    }
                    adapter!!.addList(it.list)
                    setToolBar(getString(R.string.itemShelvingLog) + ":" + itemScan)

                    val handler = Handler(Looper.getMainLooper())
                    handler.postDelayed({
                        binding.scrollView.smoothScrollTo(0, positionToReturn)
                    }, 1000)


                }
            }
        }
    }

}
