package de.hackernet.wireguardtv.ui

import android.app.Activity
import android.os.Bundle
import androidx.leanback.preference.LeanbackPreferenceFragmentCompat
import androidx.leanback.preference.LeanbackSettingsFragmentCompat
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreferenceCompat
import androidx.lifecycle.lifecycleScope
import androidx.fragment.app.FragmentActivity
import de.hackernet.wireguardtv.R
import de.hackernet.wireguardtv.data.AppSettings
import de.hackernet.wireguardtv.data.SettingsRepository
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

/**
 * Einstellungen Activity mit Leanback-optimierter Navigation
 */
class SettingsActivity : FragmentActivity() {

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

        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(android.R.id.content, SettingsFragment())
                .commit()
        }
    }
}

/**
 * Leanback Settings Fragment
 */
class SettingsFragment : LeanbackSettingsFragmentCompat() {
    
    override fun onPreferenceStartInitialScreen() {
        startPreferenceFragment(PrefsFragment())
    }

    override fun onPreferenceStartFragment(
        caller: PreferenceFragmentCompat,
        pref: Preference
    ): Boolean {
        return false
    }

    override fun onPreferenceStartScreen(
        caller: PreferenceFragmentCompat,
        pref: PreferenceScreen
    ): Boolean {
        return false
    }
}

/**
 * Preferences Fragment mit den eigentlichen Einstellungen
 */
class PrefsFragment : LeanbackPreferenceFragmentCompat() {

    private lateinit var settingsRepository: SettingsRepository
    private var currentSettings: AppSettings = AppSettings()

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        settingsRepository = SettingsRepository.getInstance(requireContext())
        
        lifecycleScope.launch {
            currentSettings = settingsRepository.getSettings()
            setupPreferences()
        }
    }

    private fun setupPreferences() {
        val context = preferenceManager.context
        val screen = preferenceManager.createPreferenceScreen(context)

        // Kategorie: Verbindung
        val connectionCategory = androidx.preference.PreferenceCategory(context).apply {
            title = "Verbindung"
        }
        screen.addPreference(connectionCategory)

        // Kill Switch
        val killSwitchPref = SwitchPreferenceCompat(context).apply {
            key = "kill_switch"
            title = "Kill Switch"
            summary = "Internet blockieren wenn VPN getrennt"
            isChecked = currentSettings.killSwitch
            setOnPreferenceChangeListener { _, newValue ->
                lifecycleScope.launch {
                    settingsRepository.updateSettings(
                        currentSettings.copy(killSwitch = newValue as Boolean)
                    )
                }
                true
            }
        }
        connectionCategory.addPreference(killSwitchPref)

        // Kategorie: Info
        val infoCategory = androidx.preference.PreferenceCategory(context).apply {
            title = "Info"
        }
        screen.addPreference(infoCategory)

        val versionPref = Preference(context).apply {
            title = "Version"
            summary = try {
                val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
                pInfo.versionName
            } catch (e: Exception) {
                "1.0.0"
            }
        }
        infoCategory.addPreference(versionPref)

        val authorPref = Preference(context).apply {
            title = "Entwickelt von"
            summary = "HackerSoft - HACKER-NET Telekommuniktion"
        }
        infoCategory.addPreference(authorPref)

        preferenceScreen = screen
    }
}
