using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;

namespace Predictalytics.Shell.Views;

/// <summary>
/// Minimale Ersatzdialoge fuer <c>MessageBox.Show</c>. Bewusst im Code aufgebaut
/// und ohne Drittanbieterpaket — es sind nur zwei Varianten noetig.
/// </summary>
public static class Dialogs
{
    public static Task ShowInfoAsync(Window owner, string title, string message) =>
        ShowAsync(owner, title, message, ["OK"]).ContinueWith(_ => { });

    public static Task ShowErrorAsync(Window owner, string title, string message) =>
        ShowAsync(owner, title, message, ["OK"]).ContinueWith(_ => { });

    public static async Task<bool> ShowConfirmAsync(Window owner, string title, string message) =>
        await ShowAsync(owner, title, message, ["Ja", "Abbrechen"]) == 0;

    private static Task<int> ShowAsync(Window owner, string title, string message, string[] buttons)
    {
        var tcs = new TaskCompletionSource<int>();

        var buttonPanel = new StackPanel
        {
            Orientation = Orientation.Horizontal,
            HorizontalAlignment = HorizontalAlignment.Right,
            Spacing = 8
        };

        var dialog = new Window
        {
            Title = title,
            SizeToContent = SizeToContent.WidthAndHeight,
            MaxWidth = 640,
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
            CanResize = false,
            ShowInTaskbar = false
        };

        for (var i = 0; i < buttons.Length; i++)
        {
            var index = i;
            var button = new Button
            {
                Content = buttons[i],
                MinWidth = 90,
                IsDefault = index == 0,
                IsCancel = index == buttons.Length - 1
            };
            button.Click += (_, _) => { tcs.TrySetResult(index); dialog.Close(); };
            buttonPanel.Children.Add(button);
        }

        dialog.Content = new StackPanel
        {
            Margin = new Avalonia.Thickness(20),
            Spacing = 16,
            Children =
            {
                new TextBlock
                {
                    Text = message,
                    TextWrapping = TextWrapping.Wrap,
                    MaxWidth = 580
                },
                buttonPanel
            }
        };

        // Schliessen ueber das Fensterkreuz zaehlt als Abbruch.
        dialog.Closed += (_, _) => tcs.TrySetResult(buttons.Length - 1);

        _ = dialog.ShowDialog(owner);
        return tcs.Task;
    }
}
