package com.gh.gamecenter.search.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.databinding.FragmentSearchTabBinding
import com.gh.gamecenter.feature.entity.SettingsEntity
import com.gh.gamecenter.search.SearchGameResultFragment
import com.gh.gamecenter.search.adapter.SearchTabAdapter
import com.gh.gamecenter.search.viewmodel.SearchTabActivityViewModel
import com.gh.gamecenter.search.viewmodel.SearchTabViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener

class SearchTabFragment : BaseFragment<Any>() {

    private lateinit var binding: FragmentSearchTabBinding

    private val activityViewModel by activityViewModels<SearchTabActivityViewModel>()

    private val viewModel by viewModels<SearchTabViewModel>()

    private lateinit var adapter: SearchTabAdapter

    private var location = ""

    private var _key: String? = null
    private var _searchType: String? = null

    override fun getLayoutId(): Int = 0

    override fun getInflatedLayout() =
        FragmentSearchTabBinding.inflate(LayoutInflater.from(context))
            .also {
                binding = it
            }.root

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

        location = arguments?.getString(EntranceConsts.KEY_LOCATION) ?: ""
        with(activityViewModel) {
            searchKeyAndType.observe(this@SearchTabFragment) { (key, type) ->
                if (key != null) {
                    _key = key
                    _searchType = type
                    viewModel.updateSearchKeyAndType(key, type)
                }
            }


        }
    }

    override fun initView(view: View?) {
        super.initView(view)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        with(activityViewModel) {
            tabs.observe(viewLifecycleOwner) {
                if (it.size > 1) {
                    initTabs(it)
                } else {
                    initSingleFragment()
                }
            }

        }
    }

    private fun initTabs(tabs: List<SettingsEntity.Search.Navigation>) {
        binding.gTabs.goneIf(false)
        binding.flContainer.goneIf(true)

        binding.tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                viewModel.trackGameSearchPageTabClick(location, tab.text?.toString(), tab.position)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })

        if (tabs.size > 5) {
            binding.tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        } else {
            binding.tabLayout.tabMode = TabLayout.MODE_FIXED
        }
        adapter = SearchTabAdapter(location, _searchType, tabs, this)
        binding.viewPager.adapter = adapter
        binding.tabLayout.setupWithViewPager(binding.viewPager)
    }

    private fun initSingleFragment() {
        binding.gTabs.goneIf(true)
        binding.flContainer.goneIf(false)
        val transaction = childFragmentManager.beginTransaction()
        val fragment = childFragmentManager.findFragmentByTag(SearchGameResultFragment::class.java.name)
            ?: SearchGameResultFragment().apply {
                arguments = Bundle().apply {
                    putBoolean(EntranceConsts.KEY_IS_AUTO_LOAD, false)
                }
            }
        transaction.replace(R.id.fl_container, fragment, SearchGameResultFragment::class.java.name)
        transaction.commitAllowingStateLoss()

    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (::binding.isInitialized) {
            binding.tabLayout.setTabTextColors(
                com.gh.gamecenter.common.R.color.text_primary.toColor(requireContext()),
                com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext())
            )

        }
    }

    companion object {

        fun newInstance(location: String) =
            SearchTabFragment().apply {
                arguments = Bundle().apply {
                    putString(EntranceConsts.KEY_LOCATION, location)
                }
            }
    }
}