package xyz.apiote.bimba.czwek.dashboard.ui.home

import android.content.Context
import android.net.ConnectivityManager
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.search.SearchView
import xyz.apiote.bimba.czwek.dashboard.MainActivity
import xyz.apiote.bimba.czwek.databinding.FragmentHomeBinding
import xyz.apiote.bimba.czwek.search.BimbaResultsAdapter

class HomeFragment : Fragment() {
	private var _binding: FragmentHomeBinding? = null
	private val binding get() = _binding!!

	private lateinit var adapter: BimbaResultsAdapter

	override fun onCreateView(
		inflater: LayoutInflater,
		container: ViewGroup?,
		savedInstanceState: Bundle?
	): View {
		_binding = FragmentHomeBinding.inflate(inflater, container, false)

		val homeViewModel =
			ViewModelProvider(this)[HomeViewModel::class.java]
		homeViewModel.queryables.observe(viewLifecycleOwner) {
			adapter.update(it)
		}

		val root = binding.root
		ViewCompat.setOnApplyWindowInsetsListener(root) { view, windowInsets ->
			val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
			view.layoutParams = (view.layoutParams as FrameLayout.LayoutParams).apply {
				topMargin = insets.top
			}
			WindowInsetsCompat.CONSUMED
		}

		val onBackPressedCallback = object :
			OnBackPressedCallback(binding.searchView.currentTransitionState == SearchView.TransitionState.SHOWN) {
			override fun handleOnBackPressed() {
				binding.searchView.hide()
			}
		}
		activity?.onBackPressedDispatcher?.addCallback(onBackPressedCallback)
		binding.searchView.addTransitionListener { _, _, newState ->
			onBackPressedCallback.isEnabled = when (newState) {
				SearchView.TransitionState.SHOWN -> true
				SearchView.TransitionState.HIDDEN -> false
				else -> false
			}
		}

		binding.searchBar.setNavigationOnClickListener {
			(context as MainActivity).onNavigationClicked()
		}
		binding.suggestionsRecycler.layoutManager = LinearLayoutManager(activity)
		adapter = BimbaResultsAdapter(layoutInflater, activity, listOf())
		binding.suggestionsRecycler.adapter = adapter

		val cm = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
		binding.searchView.editText.addTextChangedListener(
			homeViewModel.SearchBarWatcher(
				requireContext(),
				cm
			)
		)
		binding.searchView.editText.setOnKeyListener { v, keyCode, event ->
			when (keyCode) {
				KeyEvent.KEYCODE_ENTER -> {
					if (event.action == KeyEvent.ACTION_UP) {
						(context as MainActivity).onSearchClicked((v as TextView).text)
						true
					} else {
						false
					}
				}

				else -> false
			}
		}

		binding.floatingActionButton.setOnClickListener {
			(context as MainActivity).onGpsClicked(this)
		}

		return binding.root
	}

	override fun onDestroyView() {
		super.onDestroyView()
		_binding = null
	}
}