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

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentStopmapTruckPalletListBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPrintClickListener
import es.verdnatura.presentation.common.OnStopMapClickListener
import es.verdnatura.presentation.view.feature.inventario.adapter.ToolBarAdapter
import es.verdnatura.presentation.view.feature.roadmap.adapter.StopMapPalletListAdapter
import es.verdnatura.presentation.view.feature.roadmap.model.RoadStopMapTruck
import es.verdnatura.presentation.view.feature.roadmap.model.StopMapTruckPallet
import es.verdnatura.presentation.view.feature.roadmap.model.StopMapTruckPalletList
import es.verdnatura.presentation.view.feature.roadmap.model.TruckAction

class StopMapPalletListFragment(
    private var title: String,
    private var stopMap: RoadStopMapTruck,
    private var actionTruck: TruckAction
) : BaseFragment<FragmentStopmapTruckPalletListBinding, RoadMapListViewModel>(
    RoadMapListViewModel::class
) {

    private var adapter: StopMapPalletListAdapter? = null
    private var onStopMapClickListener: OnStopMapClickListener? = null
    private var originalList = listOf<StopMapTruckPallet>()
    private var indexPalletScanned = -1

    companion object {
        fun newInstance(title: String, roadMap: RoadStopMapTruck, truckAction: TruckAction) =
            StopMapPalletListFragment(title, roadMap, truckAction)
    }

    override fun onAttach(context: Context) {
        if (context is OnStopMapClickListener) onStopMapClickListener = context
        super.onAttach(context)
    }

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

    override fun init() {

        binding.mainToolbar.toolbarTitle.text = title
        binding.mainToolbar.toolbarSubtitle.visibility = View.VISIBLE

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        setToolBar()
        setEvents()
        binding.scanInput.hint = if (actionTruck == TruckAction.LOAD) {
            getString(R.string.scanForLoadTruck)
        } else {
            getString(R.string.scanForUnloadTruck)
        }
        viewModel.getPalletMatchState(
            stopMap.id, state = if (actionTruck == TruckAction.LOAD) {
                "TRUNK"
            } else {
                "STORED"
            }
        )
        super.init()
    }

    private fun setEvents() {
        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                if (!binding.scanInput.text.isNullOrEmpty()) {
                    try {

                        indexPalletScanned = originalList.indexOfFirst {
                            it.pallet == binding.scanInput.text.toString().toInt()
                        }
                        // this.originalList.getOrNull(index)?.isScanned = true

                        if (indexPalletScanned != -1) {
                            viewModel.expeditionStateAddByPallet(
                                binding.scanInput.text.toString().toInt(),
                                if (actionTruck == TruckAction.LOAD) {
                                    "TRUNK"
                                } else {
                                    "STORED"
                                }
                            )
                        } else {
                            indexPalletScanned = -1
                            ma.messageWithSound(
                                "", isPlayed = true, isError = true
                            )
                        }

                    } catch (
                        ex: Exception

                    ) {
                        indexPalletScanned = -1
                        ma.messageWithSound(
                            message = getString(R.string.errorInput),
                            isError = true,
                            isPlayed = true,
                            ""
                        )
                    }
                }
                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }
    }

    private fun setToolBar() {
        val listIcons: ArrayList<Drawable> = ArrayList()
        val iconReload: Drawable = ResourcesCompat.getDrawable(
            resources, R.drawable.ic_autorenew_black_24dp, null
        )!!
        listIcons.add(iconReload)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapter(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    when (item) {
                        iconReload -> viewModel.getStopMapTruckPalletList(stopMap.id)
                    }
                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    override fun observeViewModel() {
        with(viewModel) {
            loadStopMapTruckPalletList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull { showRoadMapList(it) }
            }
            loadResponseState.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    originalList.getOrNull(indexPalletScanned)?.isScanned = true
                    adapter!!.setList(
                        originalList.sortedWith(compareBy { it.pallet })
                            .sortedWith(compareBy { it.isScanned })
                    )
                    setSubtitlePallets(originalList)
                }
            }
        }

    }

    private fun showRoadMapList(it: StopMapTruckPalletList) {
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        originalList = it.list.sortedBy { it.pallet }.sortedBy { !it.hasMatchStateCode }
        adapter = StopMapPalletListAdapter(
            originalList, object : OnPrintClickListener {

                override fun onPrintClickListener(item: StopMapTruckPallet, entryPoint: String) {
                    ma.messageWithSound(
                        "Imprimiendo rutas nuevas ${item.pallet}", isError = false, isPlayed = true
                    )
                }
            }, action = actionTruck
        )


        binding.stopmapTruckRecyclerview.adapter = adapter
        binding.stopmapTruckRecyclerview.layoutManager = lm
        setSubtitlePallets(it.list)
    }

    private fun setSubtitlePallets(list: List<StopMapTruckPallet>) {

        binding.mainToolbar.toolbarSubtitle.text = if (list.isEmpty()) {
            "0/0"
        } else {
            getString(R.string.countTxt, (list.filter { !it.hasMatchStateCode }).size, list.size)
        }
    }

}