@using Blazored.Modal
@using Blazored.Modal.Services
@using System.Globalization

@inject Services.Lookups.ISalesLookupService SalesLookupService

<div style="zoom: 80%;">
    <div class="mb-3 d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="bi bi-search me-2"></i>Buscar producto
        </h5>
    </div>

    <input type="text"
           class="form-control mb-3"
           placeholder="Buscar productos..."
           value="@_searchTerm"
           @oninput="OnInputChanged" />

    @if (_products is null)
    {
        <p class="text-muted"><em>Escriba al menos 3 caracteres para buscar.</em></p>
    }
    else if (!_products.Any())
    {
        <p class="text-danger"><em>No se encontraron productos.</em></p>
    }
    else
    {
        <div style="max-height: 400px; overflow-y: auto;">
            <table class="table table-bordered table-hover table-sm align-middle">
                <thead class="table-primary">
                    <tr>
                        <th style="width: 10%">Código</th>
                        <th>Descripción</th>
                        <th class="text-center" style="width: 15%">Precio</th>
                        <th style="width: 10%"></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var product in _products)
                    {
                        <tr>
                            <td><span class="badge bg-light text-dark">@product.Code</span></td>
                            <td>@product.Description</td>
                            <td class="text-center">$ @product.UnitPrice.ToString("N2")</td>
                            <td>
                                <button class="btn btn-sm btn-success" @onclick="() => SelectProduct(product)">Seleccionar</button>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    }

    <div class="text-end mt-3">
        <button class="btn btn-secondary" @onclick="Cancelar">Cancelar</button>
    </div>
</div>

@code {
    [CascadingParameter] public BlazoredModalInstance ModalInstance { get; set; } = default!;

    private List<EProductLookupItem>? _products;

    private string _searchTermBacking = string.Empty;
    private string _searchTerm
    {
        get => _searchTermBacking;
        set
        {
            if (value != _searchTermBacking)
            {
                _searchTermBacking = value;
                _ = Buscar();
            }
        }
    }

    private async Task OnInputChanged(ChangeEventArgs e)
    {
        _searchTerm = e.Value?.ToString() ?? string.Empty;
        await Buscar();
    }

    private async Task Buscar()
    {
        if (_searchTerm.Length < 3)
        {
            _products = null;
            return;
        }

        _products = (await SalesLookupService.SearchProductsAsync(_searchTerm)).ToList();
        StateHasChanged();
    }

    private async Task SelectProduct(EProductLookupItem item)
    {
        await ModalInstance.CloseAsync(ModalResult.Ok(item));
    }

    private async Task Cancelar()
    {
        await ModalInstance.CancelAsync();
    }
}
