@page "/Account/Manage/TwoFactorAuthentication"

@using Microsoft.AspNetCore.Http.Features
@using Microsoft.AspNetCore.Identity
@using Wave.Data
@using Humanizer
@using System.Globalization

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityUserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject IStringLocalizer<TwoFactorAuthentication> Localizer

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

<StatusMessage />

@* ReSharper disable Html.PathError *@
<BoardComponent>
    <BoardCardComponent Heading="@Localizer["Title"]">
        @if (CanTrack) {
            @if (Is2FaEnabled) {
                <div class="hyphens-auto" lang="@CultureInfo.CurrentCulture">
                    @if (RecoveryCodesLeft == 0) {
                        <Alert Type="Alert.MessageType.Error" CanRemove="false">
                            <strong>@Localizer["Alert_NoRecoveryCodes_Title"]</strong>
                            <p>
                                <a href="Account/Manage/GenerateRecoveryCodes">@Localizer["Alert_NoRecoveryCodes_Message"]</a>
                            </p>
                        </Alert>
                    } else if (RecoveryCodesLeft == 1) {
                        <Alert Type="Alert.MessageType.Error" CanRemove="false">
                            <strong>@Localizer["Alert_OneRecoveryCode_Title"]</strong>
                            <p>
                                <a href="Account/Manage/GenerateRecoveryCodes">@Localizer["Alert_OneRecoveryCode_Message"]</a>.
                            </p>
                        </Alert>
                    } else if (RecoveryCodesLeft <= 3) {
                        <Alert Type="Alert.MessageType.Warning" CanRemove="false">
                            <strong>@string.Format(Localizer["Alert_RecoveryCodes_Title"], RecoveryCodesLeft.ToWords())</strong>
                            <p>
                                <a href="Account/Manage/GenerateRecoveryCodes">@Localizer["Alert_RecoveryCodes_Message"]</a>.
                            </p>
                        </Alert>
                    }
                </div>

                if (IsMachineRemembered) {
                    <form style="display: inline-block" @formname="forget-browser" @onsubmit="OnSubmitForgetBrowserAsync" method="post" class="w-full">
                        <AntiforgeryToken/>
                        <button type="submit" class="btn btn-error w-full my-3">
                            @Localizer["ForgetBrowser_Submit"]
                        </button>
                    </form>
                }

                <div class="flex flex-col gap-2 mt-3">
                    <a href="Account/Manage/Disable2fa" class="btn btn-error w-full">
                        @Localizer["Disable_Label"]
                    </a>
                    <a href="Account/Manage/GenerateRecoveryCodes" class="btn btn-primary w-full">
                        @Localizer["GenerateRecoveryCodes_Label"]
                    </a>
                </div>
            }

            <div class="flex flex-col gap-2 mt-3">
                <h4 class="text-xl lg:text-2xl font-bold">@Localizer["Authenticator_Title"]</h4>
                <!-- Enhanced navigation needs to be false for EnableAuthenticator since it loads JS to generate the QR code -->
                @if (!HasAuthenticator) {
                    <a href="Account/Manage/EnableAuthenticator" class="btn btn-primary w-full" data-enhance-nav="false">
                        @Localizer["AuthenticatorEnable_Label"]
                    </a>
                } else {
                    <a href="Account/Manage/EnableAuthenticator" class="btn btn-primary w-full" data-enhance-nav="false">
                        @Localizer["AuthenticatorEnable_Label"]
                    </a>
                    <a href="Account/Manage/ResetAuthenticator" class="btn btn-error w-full">
                        @Localizer["AuthenticatorReset_Label"]
                    </a>
                }
            </div>
        } else {
            <div class="alert alert-danger">
                <strong>Privacy and cookie policy have not been accepted.</strong>
                <p>You must accept the policy before you can enable two factor authentication.</p>
            </div>
        }
    </BoardCardComponent>
</BoardComponent>
@* ReSharper restore Html.PathError *@

@code {
    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;

    private bool CanTrack { get; set; }
    private bool HasAuthenticator { get; set; }
    private int RecoveryCodesLeft { get; set; }
    private bool Is2FaEnabled { get; set; }
    private bool IsMachineRemembered { get; set; }

    protected override async Task OnInitializedAsync() {
        var user = await UserAccessor.GetRequiredUserAsync(HttpContext);
        CanTrack = HttpContext.Features.Get<ITrackingConsentFeature>()?.CanTrack ?? true;
        HasAuthenticator = await UserManager.GetAuthenticatorKeyAsync(user) is not null;
        Is2FaEnabled = await UserManager.GetTwoFactorEnabledAsync(user);
        IsMachineRemembered = await SignInManager.IsTwoFactorClientRememberedAsync(user);
        RecoveryCodesLeft = await UserManager.CountRecoveryCodesAsync(user);
    }

    private async Task OnSubmitForgetBrowserAsync() {
        await SignInManager.ForgetTwoFactorClientAsync();
        RedirectManager.RedirectToCurrentPageWithStatus(Localizer["ForgetBrowser_Success"], HttpContext);
    }
}
