package com.tt.honeyDue.ui.theme

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.tt.honeyDue.storage.ThemeStorage

/**
 * ThemeManager - Singleton for managing app themes
 * Matches iOS ThemeManager functionality with persistent storage
 */
object ThemeManager {
    private const val DEFAULT_THEME_ID = "default"

    /**
     * Current theme - observable state
     */
    var currentTheme by mutableStateOf(AppThemes.Default)
        private set

    /**
     * Whether the user has opted into Android 12+ Material You dynamic color.
     * On platforms without dynamic color support this flag is still persisted
     * but `HoneyDueTheme` ignores it (falls back to `currentTheme`).
     *
     * Update via [setUseDynamicColor]. The property uses a private setter to
     * avoid a JVM signature clash with the explicit setter method that
     * persists the change to [ThemeStorage].
     */
    var useDynamicColor by mutableStateOf(false)
        private set

    /**
     * Initialize theme manager and load saved theme
     * Call this after ThemeStorage.initialize()
     */
    fun initialize() {
        val savedThemeId = ThemeStorage.getThemeId()
        if (savedThemeId != null) {
            val savedTheme = AppThemes.getThemeById(savedThemeId)
            currentTheme = savedTheme
        }
        useDynamicColor = ThemeStorage.getUseDynamicColor()
    }

    /**
     * Set theme by ID and persist the selection
     */
    fun setTheme(themeId: String) {
        val newTheme = AppThemes.getThemeById(themeId)
        currentTheme = newTheme
        ThemeStorage.saveThemeId(themeId)
    }

    /**
     * Set theme by ThemeColors object and persist the selection
     */
    fun setTheme(theme: ThemeColors) {
        setTheme(theme.id)
    }

    /**
     * Opt into / out of wallpaper-derived dynamic color (Material You).
     * Persists via [ThemeStorage] so the choice survives app restarts.
     *
     * Named `applyDynamicColor` rather than `setUseDynamicColor` to avoid a
     * JVM signature clash with the auto-generated setter for the
     * [useDynamicColor] property.
     */
    fun applyDynamicColor(enabled: Boolean) {
        useDynamicColor = enabled
        ThemeStorage.saveUseDynamicColor(enabled)
    }

    /**
     * Get all available themes
     */
    fun getAllThemes(): List<ThemeColors> {
        return AppThemes.allThemes
    }

    /**
     * Reset to default theme and persist the selection
     */
    fun resetToDefault() {
        setTheme(DEFAULT_THEME_ID)
    }
}
