@inject HttpClient Http
@inject NavigationManager NavigationManager

<div class="p-4 mb-4 mx-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 sm:p-6 dark:bg-gray-800">
    <h3 class="mb-2 text-lg font-medium text-gray-900 dark:text-white">Two-factor authentication</h3>

    @if (IsLoading)
    {
        <LoadingIndicator />
    }
    else
    {
        @if (TwoFactorEnabled)
        {
            <div class="mb-3 text-sm text-gray-600 dark:text-gray-400">Two factor authentication is currently enabled.</div>
            <Button Color="danger" OnClick="DisableTwoFactor">Disable Two-Factor Authentication</Button>
        }
        else
        {
            <div class="mb-3 text-sm text-gray-600 dark:text-gray-400">Two factor authentication is currently disabled. In order to improve your account security we advise you to enable it.</div>
            <Button Color="success" OnClick="EnableTwoFactor">Enable Two-Factor Authentication</Button>
        }
    }
</div>

@code {
    /// <summary>
    /// Gets or sets a value indicating whether Two-Factor Authentication is enabled.
    /// </summary>
    [Parameter]
    public bool TwoFactorEnabled { get; set; }

    /// <summary>
    /// Event callback that is invoked when the Two-Factor Authentication status changes.
    /// </summary>
    [Parameter]
    public EventCallback OnStatusChanged { get; set; }

    private bool IsLoading { get; set; } = true;

    /// <summary>
    /// Loads the Two-Factor Authentication status from the server.
    /// </summary>
    /// <returns>A task representing the asynchronous operation.</returns>
    public async Task LoadData()
    {
        IsLoading = true;
        StateHasChanged();

        var twoFactorResponse = await Http.GetFromJsonAsync<TwoFactorEnabledResult>("v1/TwoFactorAuth/status");
        if (twoFactorResponse is not null)
        {
            TwoFactorEnabled = twoFactorResponse.TwoFactorEnabled;
        }

        IsLoading = false;
        StateHasChanged();
    }

    /// <summary>
    /// Navigates to the Enable Two-Factor Authentication page.
    /// </summary>
    private void EnableTwoFactor()
    {
        NavigationManager.NavigateTo("settings/security/enable-2fa");
    }

    /// <summary>
    /// Navigates to the Disable Two-Factor Authentication page.
    /// </summary>
    private void DisableTwoFactor()
    {
        NavigationManager.NavigateTo("settings/security/disable-2fa");
    }

    /// <summary>
    /// Represents the result of the Two-Factor Authentication status check.
    /// </summary>
    private sealed class TwoFactorEnabledResult
    {
        /// <summary>
        /// Gets or sets a value indicating whether Two-Factor Authentication is enabled.
        /// </summary>
        public required bool TwoFactorEnabled { get; init; } = false;
    }
}
