@page "/credentials"
@inherits MainBase
@inject CredentialService CredentialService

<LayoutPageTitle>Home</LayoutPageTitle>

<PageHeader
    BreadcrumbItems="@BreadcrumbItems"
    Title="Credentials"
    Description="Find all of your credentials below.">
    <CustomActions>
        <RefreshButton OnClick="LoadCredentialsAsync" ButtonText="Refresh" />
    </CustomActions>
</PageHeader>

@if (IsLoading)
{
    <LoadingIndicator />
}

<div class="grid gap-4 px-4 mb-4 md:grid-cols-4 xl:grid-cols-6">
    @if (Credentials.Count == 0)
    {
        <div class="credential-card col-span-full p-4 space-y-2 bg-amber-50 border border-primary-500 rounded-lg shadow-sm dark:border-primary-700 dark:bg-gray-800">
            <div class="px-4 py-6 text-gray-700 dark:text-gray-200 rounded text-center flex flex-col items-center">
                <p class="mb-2 text-lg font-semibold text-primary-700 dark:text-primary-400">No credentials yet</p>
                <p class="text-sm mb-4">Create your first credential using the <span class="hidden md:inline">"+ New Alias"</span><span class="md:hidden">"+"</span> button in the top right corner.</p>
            </div>
        </div>
    }
    @foreach (var credential in Credentials)
    {
        <CredentialCard Obj="@credential"/>
    }
</div>

@code {
    private bool IsLoading { get; set; } = true;
    private List<CredentialListEntry> Credentials { get; set; } = new();

    /// <inheritdoc />
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            await LoadCredentialsAsync();
        }
    }

    private async Task LoadCredentialsAsync()
    {
        IsLoading = true;
        StateHasChanged();

        // Load the aliases from the webapi via AliasService.
        var credentialListEntries = await CredentialService.GetListAsync();
        if (credentialListEntries is null)
        {
            // Error loading aliases.
            GlobalNotificationService.AddErrorMessage("Failed to load credentials.", true);
            return;
        }
        if (credentialListEntries.Count == 0 && !DbService.Settings.TutorialDone)
        {
            // Redirect to welcome page.
            NavigationManager.NavigateTo("/welcome");
        }

        Credentials = credentialListEntries;
        IsLoading = false;
        StateHasChanged();
    }
}
