@page "/admin"
@using MudBlazor
@using OpenArchival.Blazor.AdminPages.Shared
@using OpenArchival.DataAccess
@using Microsoft.AspNetCore.Authorization
@using OpenArchival.DataAccess.FileAccessManager

@layout AdminControlPanelLayout

@attribute [Authorize(Roles =$"{UserRoles.Admin}, {UserRoles.Writer}")]
@inject IFileAccessManager FileAccessManager
@inject ISnackbar Snackbar

<h3>Admin Home</h3>

<p>Welcome to the admin panel of your website! Choose an option on the left hand side bar to configure this application.</p>

<MudPaper Class="pa-4 mt-4" Elevation="3">
    <MudText Typo="Typo.h6" Class="mb-2">Maintenance Tasks</MudText>
    <MudDivider Class="mb-4" />
    
    <div class="d-flex align-center gap-4">
        <MudButton Variant="Variant.Filled" 
                   Color="Color.Primary" 
                   OnClick="OnBackfillClicked" 
                   Disabled="@_isBackfilling"
                   StartIcon="@(_isBackfilling ? null : Icons.Material.Filled.ImageSearch)">
            @if (_isBackfilling)
            {
                <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                <MudText Class="ms-2">Backfilling Thumbnails...</MudText>
            }
            else
            {
                <MudText>Backfill Missing Thumbnails</MudText>
            }
        </MudButton>
        
        <MudText Typo="Typo.body2" Color="Color.Secondary">
            Generates thumbnails for existing images that were uploaded before the thumbnail system was implemented.
        </MudText>
    </div>
</MudPaper>

@code {
    private bool _isBackfilling = false;

    private async Task OnBackfillClicked()
    {
        _isBackfilling = true;
        StateHasChanged();

        try
        {
            var result = await FileAccessManager.BackfillThumbnailsAsync();
            Snackbar.Add($"Backfill complete: {result.Processed} processed, {result.Failed} failed.", 
                result.Failed > 0 ? Severity.Warning : Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Error during backfill: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isBackfilling = false;
            StateHasChanged();
        }
    }
}
