package com.example.cmpt362_group30_maze_game

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class LeaderboardActivity : AppCompatActivity() {

    private lateinit var tabLayout: TabLayout
    private lateinit var viewPager: ViewPager2
    private lateinit var fragmentStateAdapter:LeaderboardPagerAdapter
    private lateinit var tabTitles: Array<String>

    companion object {
        const val KEY_CURRENT_TAB = "current_tab"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_leaderboard)

        // Change colour of android status bar icons so they show on white
        WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightStatusBars = true

        // Get string array of difficulties
        tabTitles = resources.getStringArray(R.array.map_difficulties)

        // Get references to the tab layout and view pager
        tabLayout = findViewById<TabLayout>(R.id.tabLayout)
        viewPager = findViewById<ViewPager2>(R.id.viewPager)

        // Create a fragment state adapter
        fragmentStateAdapter = LeaderboardPagerAdapter(this)

        // Set the adapter for the view pager
        viewPager.adapter = fragmentStateAdapter

        // Connect the tab layout with the view pager
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = tabTitles[position]
        }.attach()

        if (savedInstanceState != null) { // Restore the current tab if the activity is being recreated
            val currentTab = savedInstanceState.getInt(KEY_CURRENT_TAB, 0)
            viewPager.setCurrentItem(currentTab, false) // Set the current tab without animation
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        // Save the ViewPager's current tab position
        outState.putInt(KEY_CURRENT_TAB, viewPager.currentItem)
    }

    //  INNER ADAPTER CLASS
    private inner class LeaderboardPagerAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {

//        Returns the total number of fragments.
        override fun getItemCount(): Int {
            return tabTitles.size
        }


//         Provides the fragment for the given position.

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> EasyFragment()
                1 -> MediumFragment()
                2 -> HardFragment()
                else -> throw IllegalArgumentException("Invalid position: $position")
            }
        }
    }



}
