@using Blazored.Modal
@using Blazored.Modal.Services
@using Domain.Entities
@inject IToastService Toast
@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 Ajuste</h5>
        </div>

        <div class="card-body">
            <div class="mb-3">
                <label class="form-label">Motivo *</label>
                <InputSelect class="form-select" @bind-Value="_model.ReasonCode">
                    <option value="">Seleccione...</option>
                    @foreach (var reason in _adjustmentReasons)
                    {
                        <option value="@reason.Code">@reason.Description</option>
                    }
                </InputSelect>
                <ValidationMessage For="@(() => _model.ReasonCode)" />
            </div>

            <div class="mb-3">
                <label class="form-label">Monto *</label>
                <InputNumber class="form-control" @bind-Value="_model.Amount" />
                <ValidationMessage For="@(() => _model.Amount)" />
            </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!;

    private QuoteAdjustmentDto _model = new();
    private List<EAdjustmentReason> _adjustmentReasons = new();

    protected override async Task OnInitializedAsync()
    {
        _adjustmentReasons = (await SalesLookupService.GetAdjustmentReasonsAsync()).ToList();
    }

    private async Task HandleValidSubmit()
    {
        if (string.IsNullOrWhiteSpace(_model.ReasonCode) || _model.Amount <= 0)
        {
            Toast.ShowError("Debe seleccionar un motivo y un monto válido.");
            return;
        }

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

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

    public class QuoteAdjustmentDto
    {
        public string ReasonCode { get; set; } = "";
        public decimal Amount { get; set; }
    }
}
