using System.IO;
using System.Text.Json;
using System.Windows;
using WPFBeginner.Models;

namespace WPFBeginner.Services;

public interface ISettingsService
{
    AppSettings Settings { get; }
    void Load();
    void Save();
    void SetLanguage(string language);
    void SetTheme(string theme);
    string CurrentLanguage { get; }
    string CurrentTheme { get; }
}

public class SettingsService : ISettingsService
{
    private readonly string _settingsPath;
    private AppSettings _settings = new();

    public AppSettings Settings => _settings;
    public string CurrentLanguage => _settings.Language;
    public string CurrentTheme => _settings.Theme;

    public SettingsService()
    {
        _settingsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
    }

    public void Load()
    {
        try
        {
            if (File.Exists(_settingsPath))
            {
                var json = File.ReadAllText(_settingsPath);
                var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
                _settings = JsonSerializer.Deserialize<AppSettings>(json, options) ?? new AppSettings();
            }
        }
        catch
        {
            _settings = new AppSettings();
        }

        ApplyLanguage(_settings.Language);
        ApplyTheme(_settings.Theme);
    }

    public void Save()
    {
        try
        {
            var options = new JsonSerializerOptions { WriteIndented = true };
            var json = JsonSerializer.Serialize(_settings, options);
            File.WriteAllText(_settingsPath, json);
        }
        catch
        {
            // Ignore save errors
        }
    }

    public void SetLanguage(string language)
    {
        _settings.Language = language;
        ApplyLanguage(language);
        Save();
    }

    public void SetTheme(string theme)
    {
        _settings.Theme = theme;
        ApplyTheme(theme);
        Save();
    }

    private void ApplyLanguage(string language)
    {
        var dict = new ResourceDictionary();
        var langFile = language == "en-US" ? "en-US" : "ko-KR";
        dict.Source = new Uri($"pack://application:,,,/Resources/Languages/{langFile}.xaml");

        // Remove existing language dictionary
        var existingLang = Application.Current.Resources.MergedDictionaries
            .FirstOrDefault(d => d.Source?.OriginalString.Contains("/Languages/") == true);
        if (existingLang != null)
        {
            Application.Current.Resources.MergedDictionaries.Remove(existingLang);
        }

        Application.Current.Resources.MergedDictionaries.Add(dict);
    }

    private void ApplyTheme(string theme)
    {
        var dict = new ResourceDictionary();
        var themeFile = theme == "LightTheme" ? "LightTheme" : "DefaultTheme";
        dict.Source = new Uri($"pack://application:,,,/Resources/Themes/{themeFile}.xaml");

        // Remove existing theme dictionary
        var existingTheme = Application.Current.Resources.MergedDictionaries
            .FirstOrDefault(d => d.Source?.OriginalString.Contains("/Themes/") == true);
        if (existingTheme != null)
        {
            Application.Current.Resources.MergedDictionaries.Remove(existingTheme);
        }

        Application.Current.Resources.MergedDictionaries.Add(dict);
    }
}
