using System.Windows;
using System.Windows.Media;

namespace NexusShell.Services;

public sealed class ThemeService
{
    private const string LightThemePath = "Themes/NexusTheme.Light.xaml";
    private ResourceDictionary? _lightThemeDictionary;

    public void Apply(string theme, ProfileService? profileService = null, string? accentColor = null)
    {
        var app = Application.Current;
        if (app is null)
        {
            return;
        }

        var merged = app.Resources.MergedDictionaries;
        RemoveLightTheme(merged);

        if (string.Equals(theme, "light", StringComparison.OrdinalIgnoreCase))
        {
            _lightThemeDictionary ??= new ResourceDictionary
            {
                Source = new Uri(LightThemePath, UriKind.Relative),
            };
            merged.Insert(0, _lightThemeDictionary);
        }

        if (!string.IsNullOrWhiteSpace(accentColor))
        {
            ApplyAccent(accentColor);
        }

        var profile = profileService?.LoadProfile();
        if (profile is null)
        {
            return;
        }

        profile.Theme = theme;
        profileService!.SaveProfile(profile);
    }

    public void ApplyAccent(string accentColor)
    {
        var app = Application.Current;
        if (app is null)
        {
            return;
        }

        var resolved = ResolveAccent(accentColor);
        var accent = resolved == "cyan"
            ? Color.FromRgb(0x00, 0xD9, 0xFF)
            : Color.FromRgb(0x8A, 0x4F, 0xFF);

        app.Resources["NexusAccentCyanBrush"] = new SolidColorBrush(accent);
        app.Resources["NexusCyanColor"] = accent;
        app.Resources["NexusCyanBrush"] = new SolidColorBrush(accent);
    }

    public static string ResolveAccent(string accentColor) =>
        accentColor.ToLowerInvariant() switch
        {
            "purple" => "purple",
            "cyan" => "cyan",
            _ => "auto",
        };

    private static void RemoveLightTheme(IList<ResourceDictionary> merged)
    {
        for (var i = merged.Count - 1; i >= 0; i--)
        {
            var source = merged[i].Source?.OriginalString;
            if (source?.Contains("NexusTheme.Light", StringComparison.OrdinalIgnoreCase) == true)
            {
                merged.RemoveAt(i);
            }
        }
    }
}
