package cl.homelogic.platform.designsystem.themes

import cl.homelogic.platform.common.logging.Trace
import cl.homelogic.platform.common.logging.TreeRoots
import cl.homelogic.platform.designsystem.foundations.Themes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

data class DesignSystemState(
    val theme: Themes,
    val darkMode: DarkModeState,
)

enum class DarkModeState {
    Disabled,
    Enabled,
    Oled,
}

class DesignSystemManager(
    theme: Themes,
    darkMode: DarkModeState,
) {
    private val _coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)

    private val _statusBarManager = StatusBarManager()

    private val _state =
        MutableStateFlow(DesignSystemState(theme, darkMode))
    val state: StateFlow<DesignSystemState> = _state

    init {
        Trace.d(TreeRoots.DesignSystem, "Initializing Design System")
    }

    fun setTheme(theme: Themes) {
        Trace.i(TreeRoots.DesignSystem, "Changing theme state to: ${theme.name}")
        _coroutineScope.launch {
            _state.emit(_state.value.copy(theme = theme))
        }
    }

    fun getTheme(): Themes = _state.value.theme

    fun getDarkMode() = _state.value.darkMode

    fun setDarkMode(darkMode: DarkModeState) {
        Trace.i(TreeRoots.DesignSystem, "Changing dark mode state to: ${darkMode.name}")
        when (darkMode) {
            DarkModeState.Disabled -> _statusBarManager.lightMode()
            DarkModeState.Enabled -> _statusBarManager.darkMode()
            DarkModeState.Oled -> _statusBarManager.darkMode()
        }

        _coroutineScope.launch {
            _state.emit(_state.value.copy(darkMode = darkMode))
        }
    }
}
