@using SteUp.Shared.Components.Layout
@using SteUp.Shared.Core.Dto

<MudDialog OnBackdropClick="Cancel">
    <DialogContent>
        <HeaderLayout SmallHeader="true" Cancel="true" OnCancel="@(() => MudDialog.Cancel())"
                      Title="Seleziona articoli"/>

        @if (!Articoli.IsNullOrEmpty())
        {
            <MudSelectExtended MultiSelection="true" ItemCollection="Articoli" SearchBox="true"
                               SearchBoxAutoFocus="true" @bind-SelectedValues="ArticoliSelected"
                               SearchFunc="SearchFunc" T="ArticoliInGrigliaDto" Virtualize="true"
                               Label="Articoli" AnchorOrigin="Origin.BottomCenter" Variant="Variant.Outlined"
                               SearchBoxPlaceholder="Descrizione articolo" SearchBoxClearable="true"
                               MultiSelectionTextFunc="MultiSelectionTextFunc" ToStringFunc="ToStringFunc"/>
        }
        else
        {
            <div class="spinner-container" style="height: unset !important; margin-bottom: 1rem;">
                <MudIcon Size="Size.Large" Color="Color.Error" Icon="@Icons.Material.Rounded.Close"/>
                <MudText>Nessun articolo trovato</MudText>
            </div>
        }
    </DialogContent>
    <DialogActions>
        @if (!Articoli.IsNullOrEmpty())
        {
            <MudButton Variant="Variant.Filled" OnClick="@Submit" Size="Size.Small" Color="Color.Primary">
                Seleziona
            </MudButton>
        }
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter] private IMudDialogInstance MudDialog { get; set; } = null!;
    [Parameter] public List<ArticoliInGrigliaDto>? Articoli { get; set; }

    private IEnumerable<ArticoliInGrigliaDto>? ArticoliSelected { get; set; }

    private void Cancel() => MudDialog.Cancel();

    private void Submit() =>
        MudDialog.Close(DialogResult.Ok(ArticoliSelected?.ToList()));

    private static bool SearchFunc(ArticoliInGrigliaDto? obj, string? searchString)
    {
        if (searchString.IsNullOrEmpty() || obj == null) return true;

        return obj.Descrizione.ContainsIgnoreCase(searchString!);
    }

    private static string? ToStringFunc(ArticoliInGrigliaDto? arg) => arg?.Descrizione;

    private static string MultiSelectionTextFunc(List<ArticoliInGrigliaDto?> arg) => 
        $"{arg.Count} selezionat{(arg.Count == 1 ? "o" : "i")}";

}