package top.yeij.cyrene.ui.theme

import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat

@Composable
fun CyreneTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    presetKey: String = "pink",
    useDynamicColor: Boolean = false,
    content: @Composable () -> Unit,
) {
    val preset = getPreset(presetKey)

    val colorScheme = when {
        useDynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
            val context = LocalContext.current
            if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
        }
        darkTheme -> buildDarkScheme(preset.darkPrimary)
        else -> buildLightScheme(preset.lightPrimary)
    }

    val view = LocalView.current
    if (!view.isInEditMode) {
        SideEffect {
            val window = (view.context as? Activity)?.window
            if (window != null) {
                window.statusBarColor = colorScheme.background.toArgb()
                window.navigationBarColor = colorScheme.background.toArgb()
                window.decorView.setBackgroundColor(colorScheme.background.toArgb())
                WindowCompat.getInsetsController(window, view).apply {
                    isAppearanceLightStatusBars = !darkTheme
                    isAppearanceLightNavigationBars = !darkTheme
                }
            } else {
                view.rootView?.setBackgroundColor(android.graphics.Color.TRANSPARENT)
            }
        }
    }

    MaterialTheme(
        colorScheme = colorScheme,
        typography = CyreneTypography,
        shapes = CyreneShapes,
        content = content,
    )
}
