@page "/stock/unitform/"
@page "/stock/unitform/{Id:int?}"

@using phronCare.UIBlazor.Services.Stock
@inject LSUnitOfMeasureService unitService
@inject NavigationManager Navigation
@inject IToastService toastService

<EditForm Model="model" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <div class="card mt-4" style="zoom:80%">
        <div class="card-header d-flex justify-content-center align-items-center">
            <h3 class="card-title m-0">@((model.Id == 0) ? "Nueva Unidad de Medida" : "Editar Unidad de Medida")</h3>
        </div>

        <div class="card-body">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label for="Name" class="form-label">Nombre</label>
                    <InputText id="Name" class="form-control" @bind-Value="model.Name" />
                    <ValidationMessage For="@(() => model.Name)" />
                </div>

                <div class="col-md-8 mb-3">
                    <label for="Descripcion" class="form-label">Descripción</label>
                    <InputText id="Descripcion" class="form-control" @bind-Value="model.Description" />
                    <ValidationMessage For="@(() => model.Description)" />
                </div>
            </div>
        </div>

        <div class="card-footer">
            <div class="d-flex justify-content-end align-items-center py-3">
                <button type="submit" class="btn btn-primary me-2">Guardar</button>
                <button type="button" class="btn btn-secondary" @onclick="Cancel">Cancelar</button>
            </div>
        </div>
    </div>
</EditForm>

@code {
    [Parameter]
    public int? Id { get; set; }

    private ELSUnitOfMeasure model = new();

    protected override async Task OnInitializedAsync()
    {
        if (Id.HasValue && Id > 0)
        {
            var result = await unitService.GetByIdAsync(Id.Value);
            if (result != null)
                model = result;
            else
                toastService.ShowError("No se pudo cargar la unidad de medida.");
        }
    }

    private async Task HandleValidSubmit()
    {
        try
        {
            if (model.Id == 0)
            {
                await unitService.CreateAsync(model);
            }
            else
            {
                await unitService.UpdateAsync(model);
            }

            toastService.ShowSuccess("Unidad guardada correctamente.");
            Navigation.NavigateTo("/stock/units");
        }
        catch (Exception ex)
        {
            toastService.ShowError($"Error al guardar: {ex.Message}");
        }
    }

    private void Cancel() => Navigation.NavigateTo("/stock/units");
}
