@using SteUp.Shared.Components.SingleElements.Card
@using SteUp.Shared.Core.Dto

<MudDialog OnBackdropClick="Cancel">
    <DialogContent>

        <div class="select-shop-content">
            <div class="shop-header">
                <div class="shop-title">
                    <MudText Typo="Typo.h5"><b>Seleziona il negozio</b></MudText>

                    <MudIconButton Icon="@Icons.Material.Rounded.Close" Size="Size.Small" OnClick="@Cancel"/>
                </div>

                <div class="input-card clearButton">
                    <MudTextField T="string?" Placeholder="Cerca..." Variant="Variant.Text"
                                  @bind-Value="FilterText" DebounceInterval="500"
                                  OnDebounceIntervalElapsed="ApplyFilters"/>
                </div>
            </div>

            <div class="shop-body">
                @if (_afterRender)
                {
                    if (FilteredList.IsNullOrEmpty())
                    {
                        <MudText Typo="Typo.body2">Nessun negozio trovato</MudText>
                    }
                    else
                    {
                        <Virtualize Items="FilteredList" Context="puntoVendita">
                            <ShopCard PuntoVendita="puntoVendita"/>
                        </Virtualize>
                    }
                }
            </div>
        </div>

    </DialogContent>
</MudDialog>

@code {
    [CascadingParameter] private IMudDialogInstance MudDialog { get; set; } = null!;

    private List<PuntoVenditaDto>? FilteredList { get; set; }
    private string? FilterText { get; set; }

    private bool _afterRender;

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

    protected override void OnInitialized()
    {
        _afterRender = false;
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (_afterRender) return;

        _afterRender = true;
        ApplyFilters();
    }

    private void ApplyFilters()
    {
        if (FilterText.IsNullOrEmpty())
        {
            FilteredList = SteupDataService.PuntiVenditaList;
        }
        else
        {
            FilteredList = SteupDataService.PuntiVenditaList.FindAll(x =>
                (x.Indirizzo != null && x.Indirizzo.ContainsIgnoreCase(FilterText!)) ||
                (x.Descrizione != null && x.Descrizione.ContainsIgnoreCase(FilterText!)) ||
                (x.CodMdep != null && x.CodMdep.ContainsIgnoreCase(FilterText!)) ||
                (x.Citta != null && x.Citta.ContainsIgnoreCase(FilterText!)) ||
                (x.Cap != null && x.Cap.ContainsIgnoreCase(FilterText!)) ||
                (x.Provincia != null && x.Provincia.ContainsIgnoreCase(FilterText!))
            );
        }

        FilteredList = FilteredList.OrderBy(x => x.CodMdep).ToList();
        StateHasChanged();
    }

}