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

import android.content.Context
import android.os.Build
import android.view.inputmethod.EditorInfo
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentBuscarItemBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.feature.buscaritem.adapter.LocationAdapter

class BuscarItemFragment(
    var itemFk: Any? = null
) : BaseFragment<FragmentBuscarItemBinding, BuscarItemViewModel>(BuscarItemViewModel::class) {

    private var adapter: LocationAdapter? = null
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null

    companion object {
        fun newInstance(entryPoint: Int?) = BuscarItemFragment(entryPoint)
    }

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

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

    @RequiresApi(Build.VERSION_CODES.O)
    override fun init() {
        binding.mainToolbar.toolbarTitle.text = getString(R.string.getubicaition)
        setEvents()
        if (itemFk != null) {
            getLocations(itemFk!!)
        }
        super.init()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setEvents() {
        binding.editItemFk.requestFocus()
        binding.editItemFk.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (binding.editItemFk.text.toString().isNotEmpty()) try {
                    getLocations(
                        itemScanValue(
                            binding.editItemFk.text.toString(), "buy", "more"
                        )
                    )
                } catch (ex: Exception) {
                    ma.messageWithSound(ex.message.toString(), true, true)
                }
                binding.editItemFk.setText("")
                ma.hideKeyboard(binding.editItemFk)
                return@setOnEditorActionListener true
            }
            false
        }

        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

    }

    private fun getLocations(itemFk: Any) {
        this.itemFk = itemFk
        viewModel.itemshelvingGetInfo(itemFk)
    }

    override fun observeViewModel() {
        with(viewModel) {
            loadLocationList.observe(viewLifecycleOwner, Observer { event ->

                event.getContentIfNotHandled().notNull {

                    try {
                        adapter = LocationAdapter(it.list, pasillerosItemClickListener!!)
                        binding.locationRecyclerview.adapter = adapter
                        binding.locationRecyclerview.layoutManager =
                            LinearLayoutManager(
                                requireContext(),
                                LinearLayoutManager.VERTICAL,
                                false
                            )
                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            message = ex.message.toString(),
                            isError = true,
                            isPlayed = true
                        )
                    }
                    binding.mainToolbar.toolbarTitle.text =
                        getString(R.string.item) + itemFk + " " + getString(R.string.visibleTotal) + it.list.sumOf { it.visible }
                }
            })
        }
    }

}
