using System.Windows;
using System.Windows.Media;
using PSLauncher.Core.Licensing;
using PSLauncher.Core.Localization;

namespace PSLauncher.App.Views;

public partial class OnboardingDialog : Window
{
    private readonly ILicenseService _licenseService;

    public bool LicenseActivated { get; private set; }

    public OnboardingDialog(ILicenseService licenseService, string? prefilledKey = null)
    {
        _licenseService = licenseService;
        InitializeComponent();
        if (!string.IsNullOrEmpty(prefilledKey)) KeyBox.Text = prefilledKey;
        KeyBox.SelectAll();
        KeyBox.Focus();
    }

    private async void OnActivate(object sender, RoutedEventArgs e)
    {
        var key = KeyBox.Text?.Trim().ToUpperInvariant() ?? string.Empty;
        if (string.IsNullOrEmpty(key) || key.Contains("XXXX"))
        {
            ShowStatus(Strings.OnboardingInvalidKey, isError: true);
            return;
        }

        ActivateButton.IsEnabled = false;
        ShowStatus(Strings.OnboardingValidating, isError: false);

        try
        {
            var resp = await _licenseService.ValidateAsync(key, CancellationToken.None);
            switch (resp.Status)
            {
                case "valid":
                    _licenseService.SaveCached(key, resp);
                    ShowStatus(Strings.OnboardingActivated(resp.OwnerName ?? "—",
                        Strings.FormatDate(resp.DownloadEntitlementUntil)), isError: false);
                    LicenseActivated = true;
                    DialogResult = true;
                    Close();
                    return;

                case "expired":
                    _licenseService.SaveCached(key, resp); // on cache quand même pour permettre de lancer les versions installées
                    ShowStatus(Strings.OnboardingExpired(Strings.FormatDate(resp.DownloadEntitlementUntil)), isError: true);
                    LicenseActivated = true;
                    DialogResult = true;
                    Close();
                    return;

                case "revoked":
                    ShowStatus(Strings.OnboardingRevoked, isError: true);
                    break;
                case "machine_limit_exceeded":
                    ShowStatus(resp.Message ?? Strings.OnboardingMachineLimit, isError: true);
                    break;
                case "invalid":
                default:
                    ShowStatus(resp.Message ?? Strings.OnboardingInvalid, isError: true);
                    break;
            }
        }
        catch (Exception ex)
        {
            ShowStatus(Strings.OnboardingServerError(ex.Message), isError: true);
        }
        finally
        {
            ActivateButton.IsEnabled = true;
        }
    }

    private void OnLater(object sender, RoutedEventArgs e)
    {
        LicenseActivated = false;
        DialogResult = false;
        Close();
    }

    private void ShowStatus(string text, bool isError)
    {
        StatusText.Text = text;
        StatusText.Foreground = isError
            ? new SolidColorBrush(Color.FromRgb(0xF8, 0x71, 0x71))
            : (System.Windows.Media.Brush)Application.Current.FindResource("Brush.Text.Secondary");
    }
}
