package uz.mobiuz.mobiservice.dev.ui.sdk.history

import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentMonitoringLocalBinding
import uz.mobiuz.mobiservice.dev.model.SharedPref
import uz.mobiuz.mobiservice.dev.ui.base.BaseFragment
import uz.mobiuz.mobiservice.dev.utils.HeaderItemDecoration
import javax.inject.Inject


@AndroidEntryPoint
class MonitoringLocalFragment : BaseFragment(R.layout.fragment_monitoring_local) {

    @Inject
    lateinit var pref: SharedPref

    private var _bn: FragmentMonitoringLocalBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val viewModel: HistoryViewModel by viewModels()
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }

    private val adapter: MonitoringAdapter by lazy { MonitoringAdapter() }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentMonitoringLocalBinding.bind(view)

        setUpUI()
        collects()

    }

    override fun setUpUI() {
        bn.apply {
            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }
            swipeToRefresh.setOnRefreshListener {
                loadData()
                swipeToRefresh.isRefreshing = false
            }
            recyclerView.apply {
                layoutManager = LinearLayoutManager(context)
                setHasFixedSize(true)
                adapter = this@MonitoringLocalFragment.adapter
                addItemDecoration(HeaderItemDecoration(this) { itemPosition ->
                    if (itemPosition >= 0 && itemPosition < adapter!!.itemCount) {
                        (adapter as MonitoringAdapter).isHeaderItem(itemPosition)
                    } else false
                })
            }
        }

    }

    private fun loadData() {
        lifecycleScope.launchWhenStarted {
            viewModel.getAllMonitoring().collect {
                bn.recyclerView.isVisible = it.isNotEmpty()
                bn.layoutEmpty.root.isVisible = it.isEmpty()
                adapter.setData(it)
            }
        }

    }


    override fun collects() {}

    override fun onDestroy() {
        _bn = null
        super.onDestroy()
    }
}