@page "/setup-2fa"
@inject IAuthService AuthService
@inject NavigationManager Navigation
@inject IJSRuntime JSRuntime
@inject ILocalizationService Loc

@rendermode InteractiveServer
@attribute [Microsoft.AspNetCore.Authorization.Authorize]

<PageTitle>@Loc["page.title.setup2fa"]</PageTitle>

<div class="auth-page">
    <div class="auth-card">
        <div class="auth-logo">
            <img src="/Assets/logo.jpg" alt="Author Buddy" />
        </div>
        <h2>@Loc["setup2fa.heading"]</h2>

        @if (isEnabled)
        {
            <div class="auth-success">
                <p>@Loc["setup2fa.status.enabled"]</p>
                <button @onclick="Disable2FA" disabled="@isBusy">@Loc["setup2fa.button.disable"]</button>
            </div>
        }
        else if (showSecret)
        {
            <p>@Loc["setup2fa.instruction"]</p>

            <div class="qr-container">
                <img src="@qrCodeDataUri" alt="QR Code" />
            </div>

            <div class="form-group">
                <label>@Loc["setup2fa.label.secret_key"]</label>
                <div class="secret-display">
                    <code>@secret</code>
                    <button @onclick="CopySecret">@Loc["common.copy"]</button>
                </div>
            </div>

            <div class="form-group">
                <label for="code">@Loc["setup2fa.label.verification_code"]</label>
                <input id="code" @bind="verificationCode" maxlength="6" @onkeydown="HandleKeyDown" />
            </div>

            <div class="auth-actions">
                <button @onclick="Enable2FA" disabled="@isBusy || string.IsNullOrWhiteSpace(verificationCode)">@Loc["setup2fa.button.enable"]</button>
                <button @onclick="Cancel">@Loc["common.cancel"]</button>
            </div>
        }
        else
        {
            <p>@Loc["setup2fa.description"]</p>
            <div class="auth-actions">
                <button @onclick="StartSetup">@Loc["setup2fa.button.setup"]</button>
            </div>
        }

        @if (!string.IsNullOrEmpty(errorMessage))
        {
            <div class="auth-error">@errorMessage</div>
        }
    </div>
</div>

@code {
    private string secret = string.Empty;
    private string verificationCode = string.Empty;
    private string errorMessage = string.Empty;
    private string? qrCodeDataUri;
    private bool showSecret;
    private bool isEnabled;
    private bool isBusy;
    private string? username;

    protected override async Task OnInitializedAsync()
    {
        isEnabled = await AuthService.Is2FAEnabledAsync();
        var user = await AuthService.GetCurrentUserAsync();
        username = user?.Name;
    }

    private async Task HandleKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
            await Enable2FA();
    }

    private async Task StartSetup()
    {
        isBusy = true;
        try
        {
            secret = await AuthService.Generate2FASecretAsync();
            var uri = AuthService.Get2FAProvisioningUri(secret, username ?? "user");
            qrCodeDataUri = await GenerateQRCodeDataUri(uri);
            showSecret = true;
        }
        catch (Exception ex)
        {
            errorMessage = $"{Loc["common.error"]} {ex.Message}";
        }
        finally
        {
            isBusy = false;
        }
    }

    private async Task Enable2FA()
    {
        if (string.IsNullOrWhiteSpace(verificationCode) || verificationCode.Length != 6)
        {
            errorMessage = Loc["setup2fa.error.invalid_code"];
            return;
        }

        if (!TotpHelper.VerifyCode(secret, verificationCode))
        {
            errorMessage = Loc["setup2fa.error.code_invalid"];
            return;
        }

        isBusy = true;
        errorMessage = string.Empty;

        try
        {
            var result = await AuthService.Enable2FAAsync(secret);
            if (result)
            {
                isEnabled = true;
                showSecret = false;
            }
            else
            {
                errorMessage = Loc["setup2fa.error.enable_failed"];
            }
        }
        catch (Exception ex)
        {
            errorMessage = $"{Loc["common.error"]} {ex.Message}";
        }
        finally
        {
            isBusy = false;
        }
    }

    private async Task Disable2FA()
    {
        isBusy = true;
        try
        {
            var result = await AuthService.Disable2FAAsync();
            if (result)
            {
                isEnabled = false;
                showSecret = false;
                secret = string.Empty;
            }
        }
        catch (Exception ex)
        {
            errorMessage = $"{Loc["common.error"]} {ex.Message}";
        }
        finally
        {
            isBusy = false;
        }
    }

    private async Task<string?> GenerateQRCodeDataUri(string uri)
    {
        try
        {
            var encoded = System.Web.HttpUtility.UrlEncode(uri);
            return $"https://api.qrserver.com/v1/create-qr-code/?size=200x200&data={encoded}";
        }
        catch
        {
            return null;
        }
    }

    private async Task CopySecret()
    {
        if (!string.IsNullOrEmpty(secret))
            await JSRuntime.InvokeVoidAsync("navigator.clipboard.writeText", secret);
    }

    private void Cancel()
    {
        Navigation.NavigateTo("/");
    }
}
