package com.mobiuz.app.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 com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentUssdBinding
import com.mobiuz.app.dev.model.ServiceData
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.ui.base.BaseFragment
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.utils.extensions.getCurrentName
import dagger.hilt.android.AndroidEntryPoint
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: FragmentPagerAdapter
    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.getCurrentName(pref.language)
                if (it.data.size == 1) {
                    tabLayout.isVisible = false
                }

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

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

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


        }
    }

    override fun collects() {

    }


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