package com.webtoonviewer.ui

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import com.google.android.material.tabs.TabLayout
import com.webtoonviewer.R
import com.webtoonviewer.utils.SharedPreferencesHelper

class DialogAutoScrollSpeedFragment: DialogFragment() {
    private lateinit var speedPreferences: SharedPreferencesHelper

    companion object {
        private const val ARG_PARAM = "param"

        fun newInstance(param: String): DialogAutoScrollSpeedFragment {
            val fragment = DialogAutoScrollSpeedFragment()
            val args = Bundle().apply {
                putString(ARG_PARAM, param)
            }
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_auto_scroll_speed, container, false)
    }

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

        speedPreferences = SharedPreferencesHelper(requireContext(), "auto_scroll_speed")

        val tabLayout: TabLayout = view.findViewById(R.id.tabLayoutDialogAutoScrollSpeed)

        // Adding tabs to TabLayout
        val tabs = listOf("1x", "2x", "3x", "4x", "5x")
        for (tab in tabs) {
            tabLayout.addTab(tabLayout.newTab().setText(tab))
        }

        val title = arguments?.getString(ARG_PARAM) ?: ""
        val textView: TextView = view.findViewById(R.id.textViewImageDialogTitle)
        textView.text = title
        val savedTab = speedPreferences.readData(title, "1x")

        // Set initial selected tab
        val initialTabIndex = tabs.indexOf(savedTab)
        tabLayout.getTabAt(initialTabIndex)?.select()

        // Handle tab selection
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.let {
                    val selectedText = it.text.toString()
                    speedPreferences.saveData(title, selectedText)
                    dismiss()
                }
            }

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