@page "/login"
@layout LoginLayout

@using JSMR.UI.Blazor.Services

@inject SessionState Session
@inject NavigationManager Nav

<h3>Login</h3>

@if (Session.IsAuthenticated)
{
    <p>You're already logged in as <b>@Session.Me?.Name</b>.</p>
    <button @onclick="Logout">Logout</button>
}
else
{
    <div style="max-width: 360px;">
        <BitCard>
            <BitStack>
                <BitTextField Label="Username" @bind-Value="username"></BitTextField>
                <BitTextField Label="Password" @bind-Value="password" Type="BitInputType.Password"></BitTextField>
                <BitButton OnClick="LoginAsync" IsEnabled="@(!busy)">Login</BitButton>
                @if (!string.IsNullOrWhiteSpace(error))
                {
                    <p style="color: crimson; margin-top: 8px;">@error</p>
                }
            </BitStack>
        </BitCard>
    </div>
}

@code {
    private string username = "";
    private string password = "";
    private bool busy;
    private string? error;

    private async Task LoginAsync()
    {
        busy = true;
        error = null;
        try
        {
            var ok = await Session.LoginAsync(username, password);
            if (!ok)
            {
                error = "Invalid username or password.";
                return;
            }

            Nav.NavigateTo("/");
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        finally
        {
            busy = false;
        }
    }

    private async Task Logout()
    {
        busy = true;
        error = null;
        try
        {
            await Session.LogoutAsync();
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        finally
        {
            busy = false;
        }
    }
}