@page "/account/security"

@using Moonlight.Core.Services
@using Moonlight.Core.UI.Components.Navigations
@using Moonlight.Core.Models.Forms
@using MoonCoreUI.Services
@using Moonlight.Core.Models.Abstractions
@using MoonCore.Exceptions
@using Moonlight.Core.UI.Components.Auth

@inject IdentityService IdentityService
@inject ToastService ToastService
@inject IAuthenticationProvider AuthenticationProvider

<div class="card card-body bg-primary mb-8">
    <div class="d-flex align-items-center">
        <span class="fs-2 fw-semibold">
            @* the @@@ looks weird, ik that, it will result in @username *@

            @@@IdentityService.CurrentUser.Username
        </span>
    </div>
</div>

<AccountNavigation Index="1"/>

<LazyLoader Load="Load">
    <div class="row g-5">
        <div class="col-md-6 col-12">
            <div class="card">
                <SmartForm Model="PasswordForm" OnValidSubmit="OnValidSubmit">
                    <div class="card-body">
                        <div class="row">
                            <AutoForm Model="PasswordForm" Columns="12" />
                        </div>
                    </div>
                    <div class="card-footer d-flex justify-content-end">
                        <button class="btn btn-primary" type="submit">Save changes</button>
                    </div>
                </SmartForm>
            </div>
        </div>
        <div class="col-md-6 col-12">
            <div class="card h-100">
                <div class="card-body">
                    <TwoFactorWizard />
                </div>
            </div>
        </div>
    </div>
</LazyLoader>

@code
{
    private readonly ChangePasswordForm PasswordForm = new();

    private Task Load(LazyLoader lazyLoader)
    {
        return Task.CompletedTask;
    }

    private async Task OnValidSubmit()
    {
        if (PasswordForm.Password != PasswordForm.RepeatedPassword)
            throw new DisplayException("The passwords do not match");
        
        await AuthenticationProvider.ChangePassword(IdentityService.CurrentUser, PasswordForm.Password);
        
        await ToastService.Success("Successfully changed password");
        await IdentityService.Authenticate(true);
    }
}