package uz.mobiuz.mobiservice.dev.ui.service

import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.google.android.material.tabs.TabLayout.MODE_SCROLLABLE
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentUssdBinding
import uz.mobiuz.mobiservice.dev.model.ServiceData
import uz.mobiuz.mobiservice.dev.model.SharedPref
import uz.mobiuz.mobiservice.dev.ui.base.BaseFragment
import uz.mobiuz.mobiservice.dev.ui.global.CONSTANTS
import dagger.hilt.android.AndroidEntryPoint
import uz.mobiuz.mobiservice.dev.utils.extensions.customLog
import javax.inject.Inject

@AndroidEntryPoint
class UssdFragment : BaseFragment(R.layout.fragment_ussd) {

    private var _bn: FragmentUssdBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")

    @Inject
    lateinit var pref: SharedPref
    private var service: ServiceData? = null
    private lateinit var adapter: ServicesPagerAdapter
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }

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

        arguments?.let {
            val arg = it.getString(CONSTANTS.SERVICE)
            service = Gson().fromJson(arg, ServiceData::class.java)
        }

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentUssdBinding.bind(view)
        setUpUI()
        collects()
    }


    override fun setUpUI() {
        bn.apply {

            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }
            service?.let {
                toolbar.title = it.title.getTranslated()
                if (it.data.size == 1) {
                    tabLayout.isVisible = false
                }

                if (it.data.size > 3) {
                    tabLayout.tabMode = MODE_SCROLLABLE
                }

                adapter = ServicesPagerAdapter(this@UssdFragment, it)
                viewPager.adapter = adapter

                TabLayoutMediator(bn.tabLayout, bn.viewPager) { tab, pos ->
                    tab.text = it.data[pos].title.getTranslated()
                }.attach()
            }


        }
    }

    override fun onStart() {
        customLog("ussd fragment onStart")
        super.onStart()
    }

    override fun onStop() {
        customLog("ussd fragment onStop")
        super.onStop()
    }

    override fun onResume() {
        customLog("ussd fragment onResume")
        super.onResume()
    }

    override fun collects() {}

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