@using Blazored.Modal
@using Blazored.Modal.Services
@using Blazored.Typeahead
@using Domain.Entities
@inject Services.Lookups.ISalesLookupService SalesLookupService

<EditForm Model="_model" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div class="card" style="zoom:90%;">
        <div class="card-header">
            <h5 class="card-title mb-0">Agregar Impuesto</h5>
        </div>

        <div class="card-body">
            <div class="mb-3">
                <label class="form-label">Tipo de Impuesto *</label>
                <BlazoredTypeahead TItem="ETaxType" TValue="ETaxType"
                                   SearchMethod="SearchTaxTypes"
                                   Value="_selectedTaxType"
                                   ValueChanged="OnTaxTypeSelected"
                                   ValueExpression="@(() => _selectedTaxType)"
                                   TextProperty="Description"
                                   Placeholder="Buscar tipo de impuesto...">
                    <ResultTemplate Context="item">
                        @item.Description (@item.Taxrate.ToString("0.#")%)
                    </ResultTemplate>
                    <SelectedTemplate Context="item">
                        @item.Description
                    </SelectedTemplate>
                </BlazoredTypeahead>
            </div>
            <div class="mb-3">
                <label class="form-label">Base Imponible *</label>
                <InputNumber class="form-control"
                             Value="_model.TaxableAmount"
                             ValueChanged="(decimal val) => OnValueChanged(val, (m, v) => m.TaxableAmount = v)"
                             ValueExpression="@(() => _model.TaxableAmount)" />
            </div>
            <div class="mb-3">
                <label class="form-label">Alícuota (%) *</label>
                <InputNumber class="form-control"
                             Value="_model.Taxrate"
                             ValueChanged="(decimal val) => OnValueChanged(val, (m, v) => m.Taxrate = v)"
                             ValueExpression="@(() => _model.Taxrate)" />
            </div>
            <div class="mb-3">
                <label class="form-label">Importe del impuesto</label>
                <InputNumber class="form-control" @bind-Value="_model.Taxamount" readonly />
            </div>

            <div class="form-check form-switch">
                <InputCheckbox class="form-check-input" @bind-Value="_model.IsIncludedInPrice" />
                <label class="form-check-label ms-2">¿Incluido en precio?</label>
            </div>
        </div>

        <div class="card-footer text-end">
            <button type="submit" class="btn btn-success">Agregar</button>
            <button type="button" class="btn btn-secondary ms-2" @onclick="Cancelar">Cancelar</button>
        </div>
    </div>
</EditForm>

@code {
    [CascadingParameter] public BlazoredModalInstance ModalInstance { get; set; } = default!;
    [Parameter] public decimal NetAmount { get; set; }
    private ETaxType? _selectedTaxType;
    private EQuoteTax _model = new();
    private List<ETaxType> _taxTypes = new();

    protected override async Task OnInitializedAsync()
    {
        _taxTypes = (await SalesLookupService.GetTaxTypesAsync()).ToList();
        _model.TaxableAmount = NetAmount;
        Recalculate();
    }

    private Task<IEnumerable<ETaxType>> SearchTaxTypes(string searchTerm)
    {
        var result = string.IsNullOrWhiteSpace(searchTerm)
            ? _taxTypes
            : _taxTypes.Where(t => t.Description.Contains(searchTerm, StringComparison.OrdinalIgnoreCase));

        return Task.FromResult(result);
    }


    private Task OnTaxTypeSelected(ETaxType selected)
    {
        _model.Taxname = selected.Description;
        _model.Taxcode = selected.TaxCode.ToString();
        _model.Taxrate = selected.Taxrate;
        Recalculate();
        return Task.CompletedTask;
    }

    private void OnValueChanged(decimal value, Action<EQuoteTax, decimal> setter)
    {
        setter(_model, value);
        Recalculate();
    }

    private void Recalculate()
    {
        _model.Taxamount = Math.Round(_model.TaxableAmount * (_model.Taxrate / 100), 2);
    }

    private async Task HandleValidSubmit()
    {
        if (string.IsNullOrWhiteSpace(_model.Taxname))
        {
            return;
        }

        await ModalInstance.CloseAsync(ModalResult.Ok(_model));
    }

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