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

import android.content.Context
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextWatcher
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentRoadmapTruckListBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnRoadMapClickListener
import es.verdnatura.presentation.view.feature.inventario.adapter.ToolBarAdapter
import es.verdnatura.presentation.view.feature.roadmap.adapter.RoadMapListAdapter
import es.verdnatura.presentation.view.feature.roadmap.model.RoadMapTruck
import es.verdnatura.presentation.view.feature.roadmap.model.RoadMapTruckList
import java.time.LocalDate
import java.time.format.DateTimeFormatter

class RoadMapListFragment(
    private var title: String
) : BaseFragment<FragmentRoadmapTruckListBinding, RoadMapListViewModel>(
    RoadMapListViewModel::class
) {

    private var adapter: RoadMapListAdapter? = null
    private var onRoadMapClickListener: OnRoadMapClickListener? = null
    private var originalList = listOf<RoadMapTruck>()

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

    override fun onAttach(context: Context) {
        if (context is OnRoadMapClickListener) onRoadMapClickListener = context
        super.onAttach(context)
    }

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

    override fun init() {

        binding.mainToolbar.toolbarTitle.text =
            LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }
        setToolBar()
        viewModel.roadMapTruckList(
            """{"where":{"or":[{"kmStart":null},{"kmEnd":null}]}}"""
         /*   """{"where": { "etd": {
        "between": ["${LocalDate.now().atTime(LocalTime.MIN)}", 
        "${
                LocalDate.now().atTime(LocalTime.MAX)
            }"]}},"order": "etd ASC"}"""*/
        )
        super.init()
    }

    private fun setFilter() {
        binding.filterTxt.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?, start: Int, count: Int, after: Int
            ) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {

                adapter!!.setList(originalList.filter { roadMapTruck ->
                    roadMapTruck.toString().contains(
                        s.toString(), ignoreCase = true
                    )
                })

            }
        })
    }

    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 -> {
                            binding.filterTxt.setText("")
                            viewModel.roadMapTruckList(
                                """{"where":{"or":[{"kmStart":null},{"kmEnd":null}]}}"""
                            )
                        }
                    }
                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    override fun observeViewModel() {
        with(viewModel) {
            loadRoadMapTruckList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull { showRoadMapList(it) }
            }

        }
    }

    private fun showRoadMapList(it: RoadMapTruckList) {
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        originalList = it.list
        adapter = RoadMapListAdapter(originalList, onRoadMapClickListener!!)
        binding.roadmapTruckRecyclerview.adapter = adapter
        binding.roadmapTruckRecyclerview.layoutManager = lm
        setFilter()
        binding.filterTxt.requestFocus()
    }
}