@page "/sales/productform"
@page "/sales/productform/{ProductId:int?}"
@using System.ComponentModel.DataAnnotations
@using phronCare.UIBlazor.Services.Sales
@using phronCare.UIBlazor.Shared.Modals

@inject ProductCategoryService ProductCategoryService
@inject BusinessUnitService BusinessUnitService
@inject ProductService ProductService
@inject NavigationManager Navigation
@inject IToastService ToastService
@inject IModalService Modal

<div class="card" style="zoom:80%">
    <div class="card-header d-flex justify-content-center align-items-center">
        <h3 class="card-title m-0">@((ProductId.HasValue ? "Editar producto" : "Nuevo producto"))</h3>
    </div>
    <div class="card-body">
        <EditForm Model="_model" OnValidSubmit="HandleValidSubmit">
            <DataAnnotationsValidator />
            <ValidationSummary />
            <div class="row mb-3">
                <div class="col-md-6">
                    <label for="Name">Nombre:</label>
                    <InputText id="Name" @bind-Value="_model.Name" class="form-control" />
                    <ValidationMessage For="@(() => _model.Name)" />
                </div>

                <div class="mb-3 col-md-6">
                    <label for="Description" class="form-label">Descripción:</label>
                    <InputTextArea id="Description" @bind-Value="_model.Description" class="form-control" rows="4" />
                    <ValidationMessage For="@(() => _model.Description)" />
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-md-6">
                    <label for="Categoryid">Categoría:</label>
                    <InputSelect id="Categoryid" @bind-Value="_model.Categoryid" class="form-control">
                        <option value="">-- Seleccionar --</option>
                        @foreach (var cat in _productCategories)
                        {
                            <option value="@cat.Id">@cat.Name</option>
                        }
                    </InputSelect>
                    <ValidationMessage For="@(() => _model.Categoryid)" />
                </div>

                <div class="col-md-6">
                    <label for="BusinessunitsId">Unidad de Negocio:</label>
                    <InputSelect id="BusinessunitsId" @bind-Value="_model.BusinessunitsId" class="form-control">
                        <option value="">-- Seleccionar --</option>
                        @foreach (var unit in _businessUnits)
                        {
                            <option value="@unit.Id">@unit.Code</option>
                        }
                    </InputSelect>
                    <ValidationMessage For="@(() => _model.BusinessunitsId)" />
                </div>
            </div>
            <div class="row mb-3">
                <div class="mb-3 col-md-4">
                    <label>Origen</label>
                    <InputSelect class="form-select" @bind-Value="_model.Origin">
                        <option value="">-- Seleccionar --</option>
                        <option value="IMPORTADO">IMPORTADO</option>
                        <option value="NACIONAL">NACIONAL</option>
                    </InputSelect>
                    <ValidationMessage For="@(() => _model.Origin)" />
                </div>

                <div class="col-md-3">
                    <label for="Baseprice">Precio Base:</label>
                    <InputNumber id="Baseprice" @bind-Value="_model.Baseprice" class="form-control" />
                    <ValidationMessage For="@(() => _model.Baseprice)" />
                </div>

                <div class="col-md-4">
                    <label>Moneda</label>
                    <InputSelect class="form-select" @bind-Value="_model.Currency">
                        <option value="">-- Seleccionar --</option>
                        <option value="ARS">🇦🇷 ARS - Peso argentino</option>
                        <option value="USD">🇺🇸 USD - Dólar estadounidense</option>
                        <option value="EUR">🇪🇺 EUR - Euro</option>
                        <option value="BRL">🇧🇷 BRL - Real brasileño</option>
                        <option value="UYU">🇺🇾 UYU - Peso uruguayo</option>
                    </InputSelect>
                    <ValidationMessage For="@(() => _model.Currency)" />
                </div>

                <div class="col-md-1 d-flex align-items-center justify-content-start mt-4">
                    <div class="form-check form-switch">
                        <InputCheckbox id="Isactive" @bind-Value="_model.Isactive" class="form-check-input" />
                        <label class="form-check-label ms-2" for="Isactive">Activo</label>
                    </div>
                </div>
            </div>
        </EditForm>
    </div>
    <div class="card-footer">
        <div class="d-flex justify-content-end align-items-center py-3">
            <button class="btn btn-primary me-2" type="button" @onclick="HandleValidSubmit" disabled="@isSaving"> @(isSaving ? "Guardando..." : "Guardar producto") </button>
            <button type="button" class="btn btn-secondary" @onclick="NavigateBack">Cancelar</button>
        </div>
    </div>

</div>

@code {
    [Parameter] public int? ProductId { get; set; }
    [Parameter] public string? returnUrl { get; set; } = "/sales/products";

    private EProduct _model = new();
    private List<EProductCategory> _productCategories = new();
    private List<EBusinessUnit> _businessUnits = new();
    private bool isSaving = false;

    protected override async Task OnInitializedAsync()
    {
        _productCategories = await ProductCategoryService.GetAllAsync();
        _businessUnits = await BusinessUnitService.GetAllAsync();

        if (ProductId.HasValue)
        {
            _model = await ProductService.GetByIdAsync(ProductId.Value);
        }
    }

    private async Task HandleValidSubmit()
    {
        var parameters = new ModalParameters();
        parameters.Add("Message", "¿Desea guardar los cambios del producto?");
        var modal = Modal.Show<ConfirmModal>("Confirmación", parameters);
        var result = await modal.Result;

        if (result.Cancelled)
            return;

        try
        {
            HttpResponseMessage response;

            if (_model.Id == 0)
                response = await ProductService.CreateAsync(_model);
            else
                response = await ProductService.UpdateAsync(_model);

            if (response.IsSuccessStatusCode)
            {
                ToastService.ShowSuccess("Producto guardado correctamente.");
                NavigateBack();
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync();
                ToastService.ShowError($"Error: {error}");
            }
        }
        catch (Exception ex)
        {
            ToastService.ShowError($"Error: {ex.Message}");
        }
    }

    private void NavigateBack()
    {
        Navigation.NavigateTo(returnUrl ?? "/sales/products");
    }
}
