@page "/createuser"
@using OnProfNext.Client.Services
@using OnProfNext.Shared.Models
@inject UserApiService UserService
@inject NavigationManager Nav

<h3>Neuen Benutzer anlegen</h3>


@if (errorMessage is not null)
{
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <strong>Fehler:</strong> @errorMessage
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
}


<EditForm Model="newUser" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div class="mb-3">
        <label>Username</label>
        <InputText class="form-control" @bind-Value="newUser.Username" />
    </div>

    <div class="mb-3">
        <label>E-Mail</label>
        <InputText class="form-control" @bind-Value="newUser.Email" />
    </div>

    <div class="mb-3">
        <label>Passwort</label>
        <InputText type="password" class="form-control" @bind-Value="newUser.PasswordHash" />
    </div>

    <div class="mb-3">
        <label>Vorname</label>
        <InputText class="form-control" @bind-Value="newUser.FirstName" />
    </div>

    <div class="mb-3">
        <label>Nachname</label>
        <InputText class="form-control" @bind-Value="newUser.LastName" />
    </div>

    <button class="btn btn-primary" type="submit">Speichern</button>
</EditForm>

@code {
    private User newUser = new();
    private string? errorMessage;

    private async Task HandleValidSubmit()
    {
        var result = await UserService.CreateUserAsync(newUser);

        if(!result.Success)
        {
            errorMessage = result.Error;
            return;
        }
        else
        {
            Nav.NavigateTo("/users");
        }


    }
}
