@using Radzen
@using System.Collections
@using System.Collections.Generic
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.JSInterop
@typeparam TValue
@inherits DropDownBase<TValue>

@if (Visible)
{
    <div @ref="@Element" @attributes="Attributes" class="@GetCssClass()" @onfocus=@this.AsNonRenderingEventHandler(OnFocus)
         style="@Style" tabindex="@(Disabled ? "-1" : $"{TabIndex}")" id="@GetId()" @onclick="@(args => OpenPopup("ArrowDown", false, true))" @onclick:preventDefault @onclick:stopPropagation
         @onkeydown="@((args) => OnKeyPress(args))" @onkeydown:preventDefault="@preventKeydown">
        <div class="rz-helper-hidden-accessible">
            <input tabindex="-1" disabled="@Disabled" style="width:100%" aria-haspopup="listbox" readonly="" type="text" id="@Name"
                   name="@Name" aria-label="@(!Multiple && internalValue != null ? PropertyAccess.GetItemOrValueFromProperty(internalValue, TextProperty) : EmptyAriaLabel)" @attributes="InputAttributes" />

        </div>

        @if (ValueTemplate != null && selectedItem != null)
        {
            <span class="rz-dropdown-label rz-inputtext" style="width:100%;" @onkeydown:stopPropagation>
                @ValueTemplate(selectedItem)
            </span>
        }
        else if (Template != null && selectedItem != null)
        {
            <span class="rz-dropdown-label rz-inputtext" style="width:100%;" @onkeydown:stopPropagation>
                @Template(selectedItem)
            </span>
        }
        else if (selectedItem != null && !Multiple)
        {
            <span class="rz-dropdown-label rz-inputtext" style="width:100%;">
                @PropertyAccess.GetItemOrValueFromProperty(selectedItem, TextProperty)
            </span>
        }
        else if ((selectedItems.Count > 0 || SelectedValue is IEnumerable && !(SelectedValue is string)) && Multiple)
        {
            var itemsToUse = SelectedValue is IEnumerable && !(SelectedValue is string) ? ((IEnumerable)SelectedValue).Cast<object>().ToHashSet() : selectedItems;
            @if (itemsToUse.Count < MaxSelectedLabels && Chips)
            {
                <div class="rz-dropdown-chips-wrapper">
                    @foreach (var item in itemsToUse)
                    {
                        <div class="rz-chip">
                            <span class="rz-chip-text" @onkeydown:stopPropagation>
                                @if (ValueTemplate != null)
                                {
                                    @ValueTemplate(item)
                                }
                                else if (Template != null)
                                {
                                    @Template(item)
                                }
                                else
                                {
                                    @GetItemOrValueFromProperty(item!, TextProperty ?? string.Empty)
                                }
                            </span>
                            <button tabindex="0" title="@(RemoveChipTitle + " " + GetItemOrValueFromProperty(item!, TextProperty ?? string.Empty))" type="button" class="rz-button rz-button-sm rz-button-icon-only rz-base rz-shade-default @(Disabled ?"rz-state-disabled":"")" @onclick:preventDefault @onclick:stopPropagation @onclick="() => OnChipRemove(item)"><RadzenIcon Icon="close" /></button>
                        </div>
                    }
                </div>
            }
            else
            {
                <label class="rz-dropdown-label rz-inputtext" style="width:100%;" @onkeydown:stopPropagation>
                    @if (itemsToUse.Count < MaxSelectedLabels)
                    {
                        @if (Template == null)
                        {
                            @(string.Join(Separator, itemsToUse.Select(i => PropertyAccess.GetItemOrValueFromProperty(i, TextProperty))))
                        }
                        else
                        {
                            var last = itemsToUse.LastOrDefault();
                            foreach (var item in itemsToUse)
                            {
                                @Template(item)@(item != last ? Separator : "")
                            }
                        }
                    }
                    else
                    {
                        @($"{itemsToUse.Count} {SelectedItemsText}")
                    }
                </label>
            }
        }
        else if (SelectedValue != null && !(SelectedValue is IEnumerable && !(SelectedValue is string)))
        {
            <span class="rz-dropdown-label rz-inputtext rz-corner-all" style="width:100%;">
                @PropertyAccess.GetItemOrValueFromProperty(SelectedValue, TextProperty)
            </span>
        }
        else if (!string.IsNullOrEmpty(Placeholder))
        {
            <span class="rz-dropdown-label rz-inputtext rz-placeholder" style="width:100%;">
                @Placeholder
            </span>
        }
        else
        {
            <span class="rz-dropdown-label rz-inputtext" style="width:100%">
                &nbsp;
            </span>
        }

        <div class="rz-dropdown-trigger  rz-corner-right">
            <span class="notranslate rz-dropdown-trigger-icon rzi rzi-chevron-down"></span>
        </div>

        <div id="@PopupID" class="@(Multiple ? "rz-multiselect-panel" : "rz-dropdown-panel")"
             style="@PopupStyle">
            <div class="rz-lookup-panel" @onkeydown="@CloseOnEscape">
                @if (AllowFiltering || HeaderTemplate != null)
                {
                    @if (HeaderTemplate != null)
                    {
                        @HeaderTemplate
                    }
                    else
                    {
                    <div class="rz-lookup-search">
                        @RenderFilter()
                        @if (ShowSearch)
                        {
                            <button tabindex="0" class="rz-button rz-button-md rz-button-icon-only rz-primary" type="button" title="@SearchTextPlaceholder" @onclick="@((args) => OnFilter(new ChangeEventArgs()))">
                                <i class="notranslate rz-button-icon-left rzi">search</i>
                            </button>
                        }
                        @if (ShowAdd)
                        {
                            <button tabindex="0" class="rz-button rz-button-md rz-button-icon-only rz-primary" style="margin-left: 5px" type="button" title="@AddAriaLabel" @onclick="@OnAddClick">
                                <i class="notranslate rz-button-icon-left rzi">add</i>
                            </button>
                        }
                    </div>
                    }
                }
                @if (Template != null)
                {
                    <RadzenDataGrid GridLines=@GridLines EmptyTemplate=@EmptyTemplate FooterTemplate=@FooterTemplate AllowVirtualization="@IsVirtualizationAllowed()" VirtualizationOverscanCount="@GetVirtualizationOverscanCount()" AllowRowSelectOnRowClick="@AllowRowSelectOnRowClick" PagerHorizontalAlign="@PagerHorizontalAlign" PagerAlwaysVisible="@PagerAlwaysVisible" Responsive="@Responsive" AllowColumnResize="@AllowColumnResize" AllowColumnPicking="@AllowColumnPicking" AllowColumnReorder="@AllowColumnReorder" ColumnWidth="@ColumnWidth" @ref="grid" Data="@(LoadData.HasDelegate ? (Data != null ? Data.Cast<object>() : Enumerable.Empty<object>()) : pagedData)" Count="@(LoadData.HasDelegate ? Count : count)" LoadData="@OnLoadData" LoadChildData="@LoadChildData"
                                    TItem="object" ColumnReordered="@ColumnReordered" ColumnResized="@ColumnResized" ColumnReordering="@ColumnReordering" ContextMenu="@ContextMenuDataGrid"
                                    CellRender="@OnCellRender" RowRender="@OnRowRender" ShowPagingSummary="@ShowPagingSummary" PagingSummaryFormat="@PagingSummaryFormat" PageSize="@PageSize" PageSizeOptions="@PageSizeOptions" PageNumbersCount="@PageNumbersCount" AllowPaging="@(!IsVirtualizationAllowed())" AllowSorting="@AllowSorting" RowSelect="@OnRowSelect" Style="@(IsVirtualizationAllowed() ? "height:285px" : "")" Density="@Density" IsLoading="@IsLoading" FirstPageTitle="@FirstPageTitle" FirstPageAriaLabel="@FirstPageAriaLabel" PrevPageAriaLabel="@PrevPageAriaLabel" PrevPageTitle="@PrevPageTitle" NextPageAriaLabel="@NextPageAriaLabel" NextPageTitle="@NextPageTitle" LastPageAriaLabel="@LastPageAriaLabel" LastPageTitle="@LastPageTitle" PageAriaLabelFormat="@PageAriaLabelFormat" PageTitleFormat="@PageTitleFormat">
                        <Columns>
                            <RadzenDataGridColumn TItem="object" Property="@TextProperty" Title="@TextProperty" Type="typeof(string)">
                                <Template>
                                    @Template(context)
                                </Template>
                            </RadzenDataGridColumn>
                        </Columns>
                    </RadzenDataGrid>
                }
                else
                {
                    if (!string.IsNullOrEmpty(TextProperty) || Columns != null)
                    {
                        <RadzenDataGrid GridLines=@GridLines EmptyTemplate=@EmptyTemplate FooterTemplate=@FooterTemplate AllowVirtualization="@IsVirtualizationAllowed()" VirtualizationOverscanCount="@GetVirtualizationOverscanCount()" AllowRowSelectOnRowClick="@AllowRowSelectOnRowClick" PagerHorizontalAlign="@PagerHorizontalAlign" PagerAlwaysVisible="@PagerAlwaysVisible" Responsive="@Responsive" AllowColumnResize="@AllowColumnResize" AllowColumnPicking="@AllowColumnPicking" AllowColumnReorder="@AllowColumnReorder" ColumnWidth="@ColumnWidth" EmptyText="@EmptyText" @ref="grid" Data="@(LoadData.HasDelegate ? (Data != null ? Data.Cast<object>() : Enumerable.Empty<object>()) : pagedData)" Count="@(LoadData.HasDelegate? Count : count)" LoadData="@OnLoadData" LoadChildData="@LoadChildData"
                                        TItem="object" ColumnReordered="@ColumnReordered" ColumnResized="@ColumnResized" ColumnReordering="@ColumnReordering" ContextMenu="@ContextMenuDataGrid"
                                        CellRender="@OnCellRender" RowRender="@OnRowRender" ShowPagingSummary="@ShowPagingSummary" PagingSummaryFormat="@PagingSummaryFormat" PageSize="@PageSize" PageSizeOptions="@PageSizeOptions" PageNumbersCount="@PageNumbersCount" AllowPaging="@(!IsVirtualizationAllowed())" AllowSorting="@AllowSorting" RowSelect="@OnRowSelect" Style="@(IsVirtualizationAllowed() ? "height:285px" : "")" Density="@Density" IsLoading="@IsLoading" FirstPageTitle="@FirstPageTitle" FirstPageAriaLabel="@FirstPageAriaLabel" PrevPageAriaLabel="@PrevPageAriaLabel" PrevPageTitle="@PrevPageTitle" NextPageAriaLabel="@NextPageAriaLabel" NextPageTitle="@NextPageTitle" LastPageAriaLabel="@LastPageAriaLabel" LastPageTitle="@LastPageTitle" PageAriaLabelFormat="@PageAriaLabelFormat" PageTitleFormat="@PageTitleFormat">
                            <Columns>
                                @if (Columns != null)
                                {
                                    @Columns
                                }
                                else
                                {
                                    <RadzenDataGridColumn TItem="object" Property="@TextProperty" Title="@TextProperty" Type="typeof(string)" />
                                }
                            </Columns>
                        </RadzenDataGrid>
                    }
                    else
                    {
                        <RadzenDataGrid GridLines=@GridLines EmptyTemplate=@EmptyTemplate FooterTemplate=@FooterTemplate AllowVirtualization="@IsVirtualizationAllowed()" VirtualizationOverscanCount="@GetVirtualizationOverscanCount()" AllowRowSelectOnRowClick="@AllowRowSelectOnRowClick" PagerHorizontalAlign="@PagerHorizontalAlign" PagerAlwaysVisible="@PagerAlwaysVisible" Responsive="@Responsive" AllowColumnResize="@AllowColumnResize" AllowColumnPicking="@AllowColumnPicking" AllowColumnReorder="@AllowColumnReorder" ColumnWidth="@ColumnWidth" EmptyText="@EmptyText" @ref="grid" Data="@(LoadData.HasDelegate ? (Data != null ? Data.Cast<object>() : Enumerable.Empty<object>()) : pagedData)" Count="@(LoadData.HasDelegate? Count : count)" LoadData="@OnLoadData" LoadChildData="@LoadChildData"
                                        TItem="object" ColumnReordered="@ColumnReordered" ColumnResized="@ColumnResized" ColumnReordering="@ColumnReordering" ContextMenu="@ContextMenuDataGrid"
                                        CellRender="@OnCellRender" RowRender="@OnRowRender" ShowPagingSummary="@ShowPagingSummary" PagingSummaryFormat="@PagingSummaryFormat" PageSize="@PageSize" PageSizeOptions="@PageSizeOptions" PageNumbersCount="@PageNumbersCount" AllowPaging="@(!IsVirtualizationAllowed())" AllowSorting="@AllowSorting" RowSelect="@OnRowSelect" Style="@(IsVirtualizationAllowed() ? "height:285px" : "")" Density="@Density" IsLoading="@IsLoading" FirstPageTitle="@FirstPageTitle" FirstPageAriaLabel="@FirstPageAriaLabel" PrevPageAriaLabel="@PrevPageAriaLabel" PrevPageTitle="@PrevPageTitle" NextPageAriaLabel="@NextPageAriaLabel" NextPageTitle="@NextPageTitle" LastPageAriaLabel="@LastPageAriaLabel" LastPageTitle="@LastPageTitle" PageAriaLabelFormat="@PageAriaLabelFormat" PageTitleFormat="@PageTitleFormat">
                            <Columns>
                                <RadzenDataGridColumn TItem="object" Property="it" Title="Item" Type="typeof(string)">
                                    <Template>
                                        @context
                                    </Template>
                                </RadzenDataGridColumn>
                            </Columns>
                        </RadzenDataGrid>
                    }
                }
            </div>
        </div>

        @if (AllowClear && (!Multiple && HasValue || Multiple && (selectedItems.Count > 0 || SelectedValue is IEnumerable)))
        {
            <i class="notranslate rz-dropdown-clear-icon rzi rzi-times" @onclick="@Clear" @onclick:stopPropagation="true"></i>
        }
    </div>
}
@code {
    internal RenderFragment RenderFilter()
    {
#if NET7_0_OR_GREATER
        return __builder => {
            <text>
                <input aria-label="@SearchAriaLabel" class="rz-lookup-search-input" id="@SearchID" @ref="@search" tabindex="0" placeholder="@SearchTextPlaceholder"
                        @onchange="@OnFilter" @onkeydown="@OnFilterKeyPress" style="@(ShowSearch ? "" : "margin-right:0px;")"
                        @bind:event="oninput" @bind:get="searchText" @bind:set=@(args => { searchText = $"{args}"; SearchTextChanged.InvokeAsync(searchText);}) />
            </text>
        };
#else
        return __builder => {
            <text>
                <input aria-label="@SearchAriaLabel" class="rz-lookup-search-input" id="@SearchID" @ref="@search" tabindex="0" placeholder="@SearchTextPlaceholder"
                        @onchange="@OnFilter" @onkeydown="@OnFilterKeyPress" value="@searchText" style="@(ShowSearch ? "" : "margin-right:0px;")"
                        @oninput=@((ChangeEventArgs args) => { searchText = $"{args.Value}"; SearchTextChanged.InvokeAsync(searchText);}) />
            </text>
        };
#endif
    }
}
