package cz.muni.sutralog.ui.list

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import cz.muni.sutralog.R
import cz.muni.sutralog.data.CategoryPresentableListItem
import cz.muni.sutralog.data.RockPresentableListItem
import cz.muni.sutralog.databinding.CategoriesListBinding
import cz.muni.sutralog.repository.CategoryRepository
import cz.muni.sutralog.repository.RockRepository
import java.time.LocalDate

class CategoryListFragment : Fragment() {

    private lateinit var binding: CategoriesListBinding
    private lateinit var categories : List<CategoryPresentableListItem>

    private val categoryRepository: CategoryRepository by lazy {
        CategoryRepository(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = CategoriesListBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        categories = categoryRepository.getAllCategories()

        val adapter = CategoryAdapter(
            onItemClick = {
                findNavController()
                    .navigate(
                        CategoryListFragmentDirections
                            .actionCategoryListToRocksList(it.id, false)
                    )
            },
        )

        val searchItem = binding.toolbar.menu.findItem(R.id.search)
        val searchView = searchItem.actionView as SearchView

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                adapter.filter.filter(newText)
                return false
            }

        })

        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerView.adapter = adapter

        adapter.submitList(categories)
    }
}


