using BackOffice.Services.DiscountCategory;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace BackOffice.Pages.AutoComplete;

public partial class DiscountCategoryMultiSelectCombo
{
    [Inject] public IDiscountCategoryService CategoryService { get; set; } = default!;

    [Parameter] public List<long> SelectedIds { get; set; } = new();
    [Parameter] public EventCallback<List<long>> SelectedIdsChanged { get; set; }
    [Parameter] public string? Label { get; set; } = "انتخاب دسته‌بندی‌ها";
    [Parameter] public bool Disabled { get; set; }

    private List<DiscountCategoryDto> _items = new();
    private HashSet<long> _internalSelectedIds = new();
    private MudSelect<long>? _selectRef;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await LoadCategoriesAsync();
        SyncInternalFromParameter();
    }

    protected override Task OnParametersSetAsync()
    {
        SyncInternalFromParameter();
        return base.OnParametersSetAsync();
    }

    private async Task LoadCategoriesAsync()
    {
        try
        {
            var tree = await CategoryService.GetCategoriesAsync(isActive: true);
            _items = FlattenCategories(tree ?? new List<DiscountCategoryDto>());
            
            // Log first few items
            if (_items.Count > 0)
            {
                foreach (var item in _items.Take(5))
                {
                }
            }
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null)
            {
            }
            _items = new List<DiscountCategoryDto>();
        }
    }

    private List<DiscountCategoryDto> FlattenCategories(List<DiscountCategoryDto> categories, string prefix = "")
    {
        var result = new List<DiscountCategoryDto>();
        foreach (var category in categories)
        {
            var catCopy = new DiscountCategoryDto
            {
                Id = category.Id,
                Title = prefix + category.Title,
                Name = category.Name,
                ParentCategoryId = category.ParentCategoryId,
                IsActive = category.IsActive
            };
            result.Add(catCopy);
            
            if (category.Children?.Any() == true)
            {
                result.AddRange(FlattenCategories(category.Children.ToList(), prefix + "  "));
            }
        }
        return result;
    }

    private void SyncInternalFromParameter()
    {
        _internalSelectedIds = SelectedIds != null
            ? SelectedIds.Where(id => id > 0).Distinct().ToHashSet()
            : new HashSet<long>();
    }

    private async Task OnSelectedValuesChangedAsync(IEnumerable<long> values)
    {
        _internalSelectedIds = values.Where(id => id > 0).Distinct().ToHashSet();
        SelectedIds = _internalSelectedIds.ToList();

        if (SelectedIdsChanged.HasDelegate)
        {
            await SelectedIdsChanged.InvokeAsync(SelectedIds);
        }
    }

    private string GetSelectedText(List<string> selectedValues)
    {
        if (selectedValues == null || selectedValues.Count == 0)
            return string.Empty;

        var titles = new List<string>();
        foreach (var val in selectedValues)
        {
            if (long.TryParse(val, out var id))
            {
                var item = _items.FirstOrDefault(x => x.Id == id);
                titles.Add(item != null ? item.Title : val);
            }
            else
            {
                titles.Add(val);
            }
        }

        return string.Join("، ", titles);
    }
}
