@page "/Account/ResendEmailConfirmation"

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

@inject UserManager<ApplicationUser> UserManager
@inject IEmailSender<ApplicationUser> EmailSender
@inject NavigationManager NavigationManager
@inject IdentityRedirectManager RedirectManager
@inject IStringLocalizer<ResendEmailConfirmation> Localizer

<HeadContent>
    <meta name="robots" content="noindex,nofollow">
</HeadContent>

<PageTitle>@Localizer["Title"]</PageTitle>

<StatusMessage Message="@Message" />

<BoardComponent CenterContent="true">
    <BoardCardComponent Heading="@Localizer["Title"]">
        <p>@Localizer["Message"]</p>

        <EditForm Model="Input" FormName="resend-email-confirmation" OnValidSubmit="OnValidSubmitAsync" method="post" class="w-full">
            <DataAnnotationsValidator />
            
            <InputLabelComponent LabelText="@Localizer["Email_Label"]" For="() => Input.Email">
                <InputText @bind-Value="Input.Email" class="input input-bordered w-full" 
                           required aria-required="true" placeholder="@Localizer["Email_Placeholder"]" />

            </InputLabelComponent>
            
            <button type="submit" class="btn btn-primary w-full">@Localizer["Email_Submit"]</button>
        </EditForm>
    </BoardCardComponent>
</BoardComponent>

@code {
    private string? Message { get; set; }

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

    private async Task OnValidSubmitAsync() {
        var user = await UserManager.FindByEmailAsync(Input.Email!);
        if (user is null) {
            Message = Localizer["Email_Success"];
            return;
        }

        string userId = await UserManager.GetUserIdAsync(user);
        string code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
        string 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 = Localizer["Email_Success"];
    }

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