@using TaxBaik.Domain.Entities
@using TaxBaik.Web.Services.AdminClients
@inject ICommonCodeBrowserClient CommonCodeClient

<MudSelect T="string"
           Value="Value"
           ValueChanged="ValueChanged"
           Label="@Label"
           Variant="@Variant"
           FullWidth="@FullWidth"
           Class="@Class"
           Required="@Required"
           Clearable="@Clearable"
           Disabled="@Disabled">
    @if (!string.IsNullOrWhiteSpace(Placeholder))
    {
        <MudSelectItem Value="@string.Empty">@Placeholder</MudSelectItem>
    }
    @foreach (var item in items)
    {
        <MudSelectItem Value="@item.CodeValue">@item.CodeName</MudSelectItem>
    }
</MudSelect>

@code {
    [Parameter] public string? Value { get; set; }
    [Parameter] public EventCallback<string?> ValueChanged { get; set; }
    [Parameter] public string Group { get; set; } = string.Empty;
    [Parameter] public string Label { get; set; } = string.Empty;
    [Parameter] public Variant Variant { get; set; } = Variant.Outlined;
    [Parameter] public bool FullWidth { get; set; } = true;
    [Parameter] public string? Class { get; set; }
    [Parameter] public bool Required { get; set; }
    [Parameter] public bool Clearable { get; set; }
    [Parameter] public bool Disabled { get; set; }
    [Parameter] public string? Placeholder { get; set; }

    private List<CommonCode> items = [];

    protected override async Task OnParametersSetAsync()
    {
        var normalizedGroup = Group?.Trim() ?? string.Empty;
        if (!string.Equals(normalizedGroup, _loadedGroup, StringComparison.OrdinalIgnoreCase))
        {
            _loadedGroup = normalizedGroup;
            items = string.IsNullOrWhiteSpace(normalizedGroup)
                ? []
                : (await CommonCodeClient.GetByGroupAsync(normalizedGroup))
                    .OrderBy(x => x.SortOrder)
                    .ThenBy(x => x.CodeName)
                    .ToList();
        }
    }

    private string? _loadedGroup;
}
