package com.sambath.kunkhmer.screen.shop

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.GridLayoutManager
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.adapter.ProductAdapter
import com.sambath.kunkhmer.app.App
import com.sambath.kunkhmer.remote.ProductInfo
import kotlinx.android.synthetic.main.fragment_shop.view.recyclerViewShop


class ShopFragment : Fragment(), ProductAdapter.OnItemClickListener {

    private var _root: View? = null
    private val binding get() = _root!!
    private var cardList: List<ProductInfo>? = null
    private lateinit var productAdapter: ProductAdapter
    private lateinit var shopViewModel: ShopViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _root = inflater.inflate(R.layout.fragment_shop, container, false)

        shopViewModel = ShopViewModel(App.injectApiService(), App.injectPrefHelper())
        productAdapter = ProductAdapter(mutableListOf(), this)
        shopViewModel.getProducts()

        binding.recyclerViewShop.apply {
            layoutManager = GridLayoutManager(context, 2)
            adapter = productAdapter
        }

        shopViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            render(it)
        })

        val searchView = binding.findViewById<SearchView>(R.id.searchView)
        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                searchView.clearFocus() // close the keyboard after submitting the query
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                filter(newText.orEmpty())
                return true
            }
        })


        return binding
    }

    private fun filter(query: String) {
        val filteredList = cardList?.filter {
            it.name.contains(query, ignoreCase = true)
        }

        productAdapter.cardList = filteredList.orEmpty().toMutableList()
        productAdapter.notifyDataSetChanged()
    }

    private fun render(state: ShopViewModel.ProductViewState) {
        if (state.isLoginSuccess) {
            if(state.productData != null) {
                productAdapter.cardList = state.productData
                cardList = productAdapter.cardList
                productAdapter.notifyDataSetChanged()
            }
        }
        // Other state handling...
    }

    override fun onItemClick(position: Int) {
    }
}