@page "/Account/ForgotPassword"

@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<ForgotPassword> Localizer

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

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

<BoardComponent CenterContent="true">
    <BoardCardComponent Heading="@Localizer["Title"]">
        <p>@Localizer["Introduction"]</p>
        <EditForm Model="Input" FormName="forgot-password" OnValidSubmit="OnValidSubmitAsync" method="post">
            <DataAnnotationsValidator />

            <InputLabelComponent LabelText="@Localizer["Email_Label"]" For="() => Input.Email">
                <InputText @bind-Value="Input.Email" class="input input-bordered w-full" autocomplete="username" 
                           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 {
    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = new();

    private async Task OnValidSubmitAsync() {
        var user = await UserManager.FindByEmailAsync(Input.Email);
        if (user is null || !(await UserManager.IsEmailConfirmedAsync(user))) {
            // Don't reveal that the user does not exist or is not confirmed
            RedirectManager.RedirectTo("Account/ForgotPasswordConfirmation");
        }

        // For more information on how to enable account confirmation and password reset please
        // visit https://go.microsoft.com/fwlink/?LinkID=532713
        string code = await UserManager.GeneratePasswordResetTokenAsync(user);
        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
        string callbackUrl = NavigationManager.GetUriWithQueryParameters(
            NavigationManager.ToAbsoluteUri("Account/ResetPassword").AbsoluteUri,
            new Dictionary<string, object?> { ["code"] = code });

        await EmailSender.SendPasswordResetLinkAsync(user, Input.Email, HtmlEncoder.Default.Encode(callbackUrl));

        RedirectManager.RedirectTo("Account/ForgotPasswordConfirmation");
    }

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