using DevExpress.Blazor;

namespace DbFirst.BlazorWebApp.Services;

public class ThemeState
{
    private readonly IThemeChangeService themeChangeService;

    public ThemeState(IThemeChangeService themeChangeService)
    {
        this.themeChangeService = themeChangeService;
    }

    public bool IsDarkMode { get; private set; }
    public string CurrentThemeName { get; private set; } = "Fluent";

    /// <summary>
    /// Themes die eine native DevExpress Dark-Variante besitzen:
    ///   - Fluent  ? Themes.Fluent.Clone(ThemeMode.Dark), verwendet --DS-* Token-System
    ///   - BlazingBerry ? Themes.BlazingDark
    /// Alle anderen Themes (Purple, OfficeWhite, BootstrapExternal) haben keine offizielle
    /// Dark-Variante; dort übernehmen CSS-Overrides auf --dxbl-grid-* Variablen die Arbeit.
    /// </summary>
    public bool IsNativeDarkTheme => IsDarkMode &&
        (CurrentThemeName == "Fluent" || CurrentThemeName == "BlazingBerry");

    public static readonly List<string> AvailableThemes = ["Fluent", "BlazingBerry", "Purple", "OfficeWhite", "BootstrapExternal"];

    public event Action? OnChange;

    public void SetTheme(string themeName)
    {
        if (CurrentThemeName == themeName) return;
        CurrentThemeName = themeName;
        ApplyTheme();
        OnChange?.Invoke();
    }

    public void SetDarkMode(bool isDarkMode)
    {
        if (IsDarkMode == isDarkMode) return;
        IsDarkMode = isDarkMode;
        ApplyTheme();
        OnChange?.Invoke();
    }

    private void ApplyTheme()
    {
        if (CurrentThemeName == "Fluent")
        {
            var theme = Themes.Fluent.Clone(properties =>
            {
                properties.Mode = IsDarkMode ? ThemeMode.Dark : ThemeMode.Light;
                properties.ApplyToPageElements = true;
            });
            themeChangeService.SetTheme(theme);
        }
        else if (CurrentThemeName == "BlazingBerry") themeChangeService.SetTheme(IsDarkMode ? Themes.BlazingDark : Themes.BlazingBerry);
        else if (CurrentThemeName == "Purple")           themeChangeService.SetTheme(Themes.Purple);
        else if (CurrentThemeName == "OfficeWhite")      themeChangeService.SetTheme(Themes.OfficeWhite);
        else if (CurrentThemeName == "BootstrapExternal") themeChangeService.SetTheme(Themes.BootstrapExternal);
        else
            themeChangeService.SetTheme(Themes.Fluent);
    }
}