namespace GestionaDenunciasAN.Services;

public enum UiDialogTone
{
    Information,
    Warning,
    Danger
}

public sealed class UiDialogService
{
    private TaskCompletionSource<bool>? _pendingConfirmation;

    public event Action? Changed;

    public bool IsVisible { get; private set; }
    public string Title { get; private set; } = string.Empty;
    public string Message { get; private set; } = string.Empty;
    public string ConfirmText { get; private set; } = "Continuar";
    public string CancelText { get; private set; } = "Cancelar";
    public UiDialogTone Tone { get; private set; } = UiDialogTone.Warning;

    public Task<bool> ConfirmAsync(
        string title,
        string message,
        string confirmText = "Continuar",
        string cancelText = "Cancelar",
        UiDialogTone tone = UiDialogTone.Warning)
    {
        _pendingConfirmation?.TrySetResult(false);

        Title = title.Trim();
        Message = message.Trim();
        ConfirmText = confirmText.Trim();
        CancelText = cancelText.Trim();
        Tone = tone;
        IsVisible = true;

        _pendingConfirmation = new TaskCompletionSource<bool>(
            TaskCreationOptions.RunContinuationsAsynchronously);

        Changed?.Invoke();
        return _pendingConfirmation.Task;
    }

    public void Confirm()
    {
        Complete(true);
    }

    public void Cancel()
    {
        Complete(false);
    }

    private void Complete(bool confirmed)
    {
        var pendingConfirmation = _pendingConfirmation;
        _pendingConfirmation = null;
        IsVisible = false;
        Changed?.Invoke();
        pendingConfirmation?.TrySetResult(confirmed);
    }
}
