@using CMSMicroservice.Protobuf.Protos.User

<MudAutocomplete T="SearchResultItem"
                 @ref="_autocomplete"
                 Placeholder="جستجوی کاربر، صفحه..."
                 DebounceInterval="400"
                 SearchFunc="@SearchAsync"
                 ToStringFunc="@(e => e?.DisplayText ?? "")"
                 ValueChanged="@OnItemSelected"
                 Variant="Variant.Outlined"
                 Margin="Margin.Dense"
                 Dense="true"
                 Clearable="true"
                 ShowProgressIndicator="true"
                 CoerceText="false"
                 ResetValueOnEmptyText="true"
                 Adornment="Adornment.Start"
                 AdornmentIcon="@Icons.Material.Filled.Search"
                 AdornmentColor="Color.Default"
                 Class="global-search"
                 Style="max-width: 320px; min-width: 220px;">
    <ItemTemplate>
        <MudStack Row AlignItems="AlignItems.Center" Spacing="2">
            <MudIcon Icon="@context.Icon" Size="Size.Small" Color="@context.IconColor" />
            <MudStack Spacing="0">
                <MudText Typo="Typo.body2">@context.DisplayText</MudText>
                @if (!string.IsNullOrEmpty(context.Subtitle))
                {
                    <MudText Typo="Typo.caption" Color="Color.Secondary">@context.Subtitle</MudText>
                }
            </MudStack>
        </MudStack>
    </ItemTemplate>
    <NoItemsTemplate>
        <MudText Typo="Typo.body2" Class="pa-2" Color="Color.Secondary">نتیجه‌ای یافت نشد</MudText>
    </NoItemsTemplate>
</MudAutocomplete>

@code {
    [Inject] public UserContract.UserContractClient UserClient { get; set; } = default!;

    private MudAutocomplete<SearchResultItem>? _autocomplete;

    private static readonly List<SearchResultItem> QuickPages = new()
    {
        new("داشبورد", "/", Icons.Material.Filled.Dashboard, Color.Primary, "صفحه اصلی"),
        new("کاربران", "/user", Icons.Material.Filled.People, Color.Info, "مدیریت کاربران"),
        new("سفارش‌ها", "/userorder", Icons.Material.Filled.ReceiptLong, Color.Warning, "سفارش‌های کاربران"),
        new("محصولات", "/products", Icons.Material.Filled.ShoppingBag, Color.Success, "لیست محصولات"),
        new("درخواست‌های برداشت", "/commission/withdrawals", Icons.Material.Filled.RequestQuote, Color.Error, "کمیسیون"),
        new("داشبورد کمیسیون", "/commission/dashboard", Icons.Material.Filled.Assessment, Color.Primary, "کمیسیون"),
        new("اعضای باشگاه", "/club/members", Icons.Material.Filled.Groups, Color.Info, "باشگاه مشتریان"),
        new("پکیج‌ها", "/packages", Icons.Material.Filled.Inventory2, Color.Warning, "فروشگاه"),
        new("کیف‌پول", "/wallets", Icons.Material.Filled.AccountBalanceWallet, Color.Success, "مدیریت"),
        new("مدیریت سیستم", "/system/configuration", Icons.Material.Filled.Tune, Color.Default, "سیستم"),
        new("تنظیمات", "/settings", Icons.Material.Filled.Settings, Color.Default, "سیستم"),
        new("درخت شبکه", "/network/tree", Icons.Material.Filled.AccountTree, Color.Primary, "شبکه"),
        new("انبارداری", "/inventory", Icons.Material.Filled.Warehouse, Color.Warning, "انبار"),
        new("پیام‌های عمومی", "/public-messages", Icons.Material.Filled.Campaign, Color.Info, "محتوا"),
        new("بلاگ", "/blog/posts", Icons.Material.Filled.Article, Color.Success, "محتوا"),
    };

    private async Task<IEnumerable<SearchResultItem>> SearchAsync(string value, CancellationToken ct)
    {
        var results = new List<SearchResultItem>();

        if (string.IsNullOrWhiteSpace(value) || value.Length < 2)
            return results;

        // 1) Quick page navigation matches
        var pageMatches = QuickPages
            .Where(p => p.DisplayText.Contains(value, StringComparison.OrdinalIgnoreCase)
                     || p.Subtitle?.Contains(value, StringComparison.OrdinalIgnoreCase) == true)
            .Take(4)
            .ToList();
        results.AddRange(pageMatches);

        // 2) User search via gRPC
        try
        {
            var request = new GetAllUserByFilterRequest
            {
                PaginationState = new() { PageNumber = 1, PageSize = 6 },
                Filter = new() { SearchText = value }
            };

            var response = await UserClient.GetAllUserByFilterAsync(request, cancellationToken: ct);
            if (response?.Models != null)
            {
                foreach (var user in response.Models)
                {
                    results.Add(new SearchResultItem(
                        $"{user.FirstName} {user.LastName}",
                        $"/network/user-info/{user.Id}",
                        Icons.Material.Filled.Person,
                        Color.Tertiary,
                        user.Mobile));
                }
            }
        }
        catch
        {
            // Silently ignore search errors
        }

        return results;
    }

    private void OnItemSelected(SearchResultItem? item)
    {
        if (item?.Href != null)
        {
            Navigation.NavigateTo(item.Href);
            // Clear the autocomplete after navigation
            _ = Task.Run(async () =>
            {
                await Task.Delay(100);
                await InvokeAsync(StateHasChanged);
            });
        }
    }

    public record SearchResultItem(string DisplayText, string? Href, string Icon, Color IconColor, string? Subtitle = null);
}
