@page "/categories"

@namespace OpenArchival.Blazor.AdminPages.Shared
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.EntityFrameworkCore
@using Microsoft.Extensions.Logging
@using MudBlazor
@using OpenArchival.DataAccess;

@inject IDialogService DialogService 
@inject IArchiveCategoryProvider CategoryProvider;
@inject IDbContextFactory<ApplicationDbContext> DbContextFactory;
@inject ILogger<ViewAddCategoriesComponent> Logger;

<CategoriesListComponent 
    @ref=_categoriesListComponent 
    ListItemClickedCallback="ShowFilledDialog" 
    ShowDeleteButton=true
    OnDeleteClickedCallback="DeleteCategory">
    <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="OnAddClick">Add Category</MudButton>
</CategoriesListComponent>


@code {
    CategoriesListComponent _categoriesListComponent = default!;

    private async Task DeleteCategory(ArchiveCategory category)
    {
        // 1. Show a confirmation dialog (recommended)
        var confirmed = await DialogService.ShowMessageBox("Confirm", $"Delete {category.Name}?", yesText:"Delete", cancelText:"Cancel");
        if (confirmed != true) return;

        await CategoryProvider.DeleteCategoryAsync(category);
        await _categoriesListComponent.RefreshData(); 
        StateHasChanged();
    }

    private async Task ShowFilledDialog(ArchiveCategory category)
    {
        CategoryValidationModel validationModel = CategoryValidationModel.FromArchiveCategory(category);

        var parameters = new DialogParameters { ["ValidationModel"] = validationModel, ["IsUpdate"] = true, ["OriginalName"] = category.Name};

        var options = new DialogOptions { CloseOnEscapeKey = true, BackdropClick=false};

        var dialog = await DialogService.ShowAsync<CategoryCreatorDialog>("Create a Category", parameters, options);
        var result = await dialog.Result;

        if (result is not null && !result.Canceled && _categoriesListComponent is not null)
        {
            if (result.Data is null)
            {
                Logger.LogError($"The new category received by the result had a null data result member.");
                throw new NullReferenceException($"The new category received by the result had a null data result member."); 
            }

            CategoryValidationModel model = (CategoryValidationModel)result.Data;
            CategoryValidationModel.UpdateArchiveValidationModel(model, category);

            await using var context = await DbContextFactory.CreateDbContextAsync();
            await context.SaveChangesAsync();

            StateHasChanged();
            await _categoriesListComponent.RefreshData(); 
        }
    }

    private async Task OnAddClick()
    {
        var options = new DialogOptions { CloseOnEscapeKey = true, BackdropClick=false };
        var dialog = await DialogService.ShowAsync<CategoryCreatorDialog>("Create a Category", options);

        var result = await dialog.Result; 

        if (result is not null && !result.Canceled && _categoriesListComponent is not null && result.Data is not null)
        {
            await using var context = await DbContextFactory.CreateDbContextAsync();
            CategoryValidationModel model = (CategoryValidationModel)result.Data;
            context.ArchiveCategories.Add(CategoryValidationModel.ToArchiveCategory(model));

            await context.SaveChangesAsync();
            StateHasChanged();
            await _categoriesListComponent.RefreshData(); 
        }
    }
}