package mg.dot.feufaro

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import mg.dot.feufaro.config.AppConfigJson
import mg.dot.feufaro.config.DisplayConfig
import java.util.prefs.Preferences
import com.russhwolf.settings.Settings

@Serializable
data class AppConfigJson(
    val themeMode: String? = null,
    val fontSize: Float? = null,
    val playlist: List<String>? = null,
    val buttonContainerColorHex: String? = null,
    val buttonContentColorHex: String? = null,
    val buttonDisabledContainerColorHex: String? = null,
    val buttonDisabledContentColorHex: String? = null
)

fun AppConfigJson.toDisplayConfig(defaultConfig: DisplayConfig): DisplayConfig {
    return DisplayConfig(
        themeMode = this.themeMode,
        fontSize = this.fontSize,
        playlist = this.playlist,
        buttonContainerColorHex = this.buttonContainerColorHex,
        buttonContentColorHex = this.buttonContentColorHex,
        buttonDisabledContainerColorHex = this.buttonDisabledContainerColorHex,
        buttonDisabledContentColorHex = this.buttonDisabledContentColorHex
    )
}
class DisplayConfigManager(
    private val fileRepository: FileRepository,
    private val settings: Settings
)
{
    private val _displayConfig = MutableStateFlow(DisplayConfig())
    val displayConfig: StateFlow<DisplayConfig> = _displayConfig.asStateFlow()
    private val configScope = CoroutineScope(Dispatchers.Default)

    init {
        loadInitialConfig()
    }

    private fun loadInitialConfig() {
        configScope.launch {
            loadConfigFromFile("assets://config.json")

            val jsonConfig = _displayConfig.value
            val finalTheme = settings.getString("themeMode", jsonConfig.themeMode)
            val finalFontSize = settings.getFloat("fontSize", jsonConfig.fontSize)

            val pBlue = settings.getString("primaryBlueHex", jsonConfig.primaryBlueHex)
            val aYellow = settings.getString("accentYellowHex", jsonConfig.accentYellowHex)
            val aGreen = settings.getString("accentGreenHex", jsonConfig.accentGreenHex)
            val aPink = settings.getString("accentPinkHex", jsonConfig.accentPinkHex)

            _displayConfig.value = jsonConfig.copy(
                themeMode = finalTheme,
                fontSize = finalFontSize,
                primaryBlueHex = pBlue,
                accentYellowHex = aYellow,
                accentGreenHex = aGreen,
                accentPinkHex = aPink
            )
        }
    }
    fun updateCustomColor(key: String, hexValue: String) {
        settings.putString(key, hexValue)

        _displayConfig.value = when(key) {
            "primaryBlueHex" -> _displayConfig.value.copy(primaryBlueHex = hexValue)
            "accentYellowHex" -> _displayConfig.value.copy(accentYellowHex = hexValue)
            "accentGreenHex" -> _displayConfig.value.copy(accentGreenHex = hexValue)
            "accentPinkHex" -> _displayConfig.value.copy(accentPinkHex = hexValue)
            else -> _displayConfig.value
        }
    }
    suspend fun loadConfigFromFile(filePath: String) {
        try {
            val jsonString = fileRepository.readFileContent(filePath)
            val appConfigJson = Json.decodeFromString<AppConfigJson>(jsonString)
            _displayConfig.value = appConfigJson.toDisplayConfig(_displayConfig.value)

        } catch (e: Exception) {
            println("DisplayConfigManager Error 22: ${e.message}")
            e.printStackTrace()
        }
    }

    fun updateThemeMode(themeMode: String) {
        settings.putString("themeMode", themeMode)
        _displayConfig.value = _displayConfig.value.copy(themeMode = themeMode)
    }

    fun updateFontSize(fontSize: Float) {
        settings.putFloat("fontSize", fontSize)
        _displayConfig.value = _displayConfig.value.copy(fontSize = fontSize)
    }

    fun resetToDefault() {
        try {
            settings.remove("themeMode")
            settings.remove("fontSize")
            settings.remove("primaryBlueHex")
            settings.remove("accentYellowHex")
            settings.remove("accentGreenHex")
            settings.remove("accentPinkHex")

            loadInitialConfig()
        } catch (e: Exception) {
            println("Erreur lors de la réinitialisation : ${e.message}")
        }
    }
    // NOUVELLE MÉTHODE : Pour basculer le mode débogage
}