@page "/Account/ResendEmailConfirmation"

@using System.ComponentModel.DataAnnotations
@using System.Text
@using System.Text.Encodings.Web
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.WebUtilities
@using OpenArchival.Blazor.Data

@inject UserManager<ApplicationUser> UserManager
@inject IEmailSender<ApplicationUser> EmailSender
@inject NavigationManager NavigationManager
@inject IdentityRedirectManager RedirectManager

<PageTitle>Resend email confirmation</PageTitle>

<MudText Typo="Typo.h3" GutterBottom="true">Resend email confirmation</MudText>

<MudText Typo="Typo.body1" GutterBottom="true">Enter your email.</MudText>

<StatusMessage Message="@message" />

<EditForm Model="Input" FormName="resend-email-confirmation" OnValidSubmit="OnValidSubmitAsync" method="post">
    <DataAnnotationsValidator />

    <MudGrid>
        <MudItem md="12">
            <MudStaticTextField For="@(() => Input.Email)" @bind-Value="Input.Email"
                                Label="Email" Placeholder="name@example.com"
                                UserAttributes="@(new() { { "autocomplete", "username" }, { "aria-required", "true" } } )" />
        </MudItem>
        <MudItem md="12">
            <MudStaticButton Variant="Variant.Filled" Color="Color.Primary" FullWidth="true" FormAction="FormAction.Submit">Resend</MudStaticButton>
        </MudItem>
    </MudGrid>
</EditForm>

@code {
    private string? message;

    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = new();

    private async Task OnValidSubmitAsync()
    {
        var user = await UserManager.FindByEmailAsync(Input.Email!);
        if (user is null)
        {
            message = "Verification email sent. Please check your email.";
            return;
        }

        var userId = await UserManager.GetUserIdAsync(user);
        var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
        var callbackUrl = NavigationManager.GetUriWithQueryParameters(
            NavigationManager.ToAbsoluteUri("Account/ConfirmEmail").AbsoluteUri,
            new Dictionary<string, object?> { ["userId"] = userId, ["code"] = code });
        await EmailSender.SendConfirmationLinkAsync(user, Input.Email, HtmlEncoder.Default.Encode(callbackUrl));

        message = "Verification email sent. Please check your email.";
    }

    private sealed class InputModel
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; } = "";
    }
}
