using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace RpgRoller.Components.Pages.HomeControls;

[ExcludeFromCodeCoverage]
public partial class RolemasterSkillRollModal
{
    protected override void OnParametersSet()
    {
        CurrentModifierText = ModifierText;
        if (!Visible || WasVisible)
        {
            WasVisible = Visible;
            return;
        }

        PendingFocus = true;
        WasVisible = true;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!Visible || !PendingFocus)
            return;

        PendingFocus = false;
        await ModifierInputElement.FocusAsync();
    }

    private Task OnModifierInput(ChangeEventArgs args)
    {
        CurrentModifierText = args.Value?.ToString() ?? string.Empty;
        return ModifierTextChanged.InvokeAsync(CurrentModifierText);
    }

    private Task SubmitAsync()
    {
        return ConfirmRequested.InvokeAsync(CurrentModifierText);
    }

    private Task HandleOverlayClickAsync()
    {
        if (IsMutating || IsSubmitting)
            return Task.CompletedTask;

        return CancelRequested.InvokeAsync();
    }

    private Task HandleKeyDownAsync(KeyboardEventArgs args)
    {
        if ((IsMutating || IsSubmitting) || !string.Equals(args.Key, "Escape", StringComparison.Ordinal))
            return Task.CompletedTask;

        return CancelRequested.InvokeAsync();
    }

    private bool PendingFocus { get; set; }
    private bool WasVisible { get; set; }
    private string CurrentModifierText { get; set; } = string.Empty;
    private ElementReference ModifierInputElement { get; set; }

    [Parameter] public bool Visible { get; set; }

    [Parameter] public string SkillName { get; set; } = string.Empty;

    [Parameter] public string Expression { get; set; } = string.Empty;

    [Parameter] public string ModifierText { get; set; } = string.Empty;

    [Parameter] public EventCallback<string> ModifierTextChanged { get; set; }

    [Parameter] public string? ErrorMessage { get; set; }

    [Parameter] public bool IsMutating { get; set; }

    [Parameter] public bool IsSubmitting { get; set; }

    [Parameter] public string ModifierInputId { get; set; } = "rolemaster-situational-modifier";

    [Parameter] public EventCallback<string> ConfirmRequested { get; set; }

    [Parameter] public EventCallback CancelRequested { get; set; }
}