@inherits ComponentBase
@implements IDisposable

<PageTitle>@Title</PageTitle>

<div class="mt-4 ml-0">
    <div class="d-flex">
        <div>
            <MudStack Row="true">
                <MudBreadcrumbs Items="Breadcrumbs" Style="padding: 0px;" />
            </MudStack>
        </div>
        @if (LoadData is not null && DisableReload is false)
        {
            <div class="ml-auto">
                @if (Loading)
                {
                        <MudProgressCircular Color="Color.Primary" Size="Size.Small" Indeterminate="true" Style="padding: 0px; display: inherit;" />
                }
                else
                {
                        <MudIconButton OnClick="OnRefreshAsync" Icon="@Icons.Material.Filled.Refresh" Size="Size.Medium" Color="Color.Inherit" Style="padding: 0px;" />
                }
            </div>
        }
    </div>
</div>

<div class="mt-5">
    @if (Content is not null)
    {
        @Content
    }
</div>

@code{
    [Parameter] public string Title { get; set; } = Global.Name;
    [Parameter] public List<BreadcrumbItem>? Breadcrumbs { get; set; }
    [Parameter] public RenderFragment? BreadcrumbAction { get; set; }
    [Parameter] public RenderFragment? Content { get; set; }
    [Parameter] public Func<Task>? LoadData { get; set; }
    [Parameter] public bool DisableReload { get; set; }

    private bool _disposed;

    private bool _loading;
    private bool Loading
    {
        get => _loading;
        set
        {
            if (value != _loading)
            {
                _loading = value;
                StateHasChanged();
            }
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender) await OnRefreshAsync();
    }

    private async Task OnRefreshAsync()
    {
        if (LoadData is null || Loading) return;

        try
        {
            Loading = true;
            await LoadData();
        }
        finally
        {
            Loading = false;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (_disposed is false) return;
        if (disposing is false) return;

        try
        {

        }
        finally
        {
            _disposed = true;
        }
    }
}