@page "/stock/productimport"
@using Domain.Dtos.Stock
@using phronCare.UIBlazor.Services.Stock

@inject IJSRuntime JS
@inject IToastService toastService
@inject NavigationManager Navigation
@inject LSProductService productService

<h3 class="mb-4">Importación masiva de productos</h3>

<div class="mb-3">
    <button class="btn btn-primary" @onclick="DownloadTemplate">Descargar plantilla Excel</button>
</div>

<div class="mb-4">
    <label for="fileUpload" class="form-label fw-semibold">Seleccionar archivo Excel</label>
    <div class="input-group">
        <label class="input-group-text bg-light border-secondary" for="fileUpload">📎</label>
        <InputFile id="fileUpload" class="form-control" OnChange="HandleFileSelected" accept=".xlsx" />
    </div>
</div>

@if (UploadedFile != null)
{
    <div class="mb-4">
        <div class="mb-4">
            <button class="btn btn-warning" @onclick="ProcessFile">Procesar archivo Excel</button>
        </div>
    </div>
}

@if (PreviewItems != null)
{
    <h5 class="mt-4">Vista previa</h5>
    <table class="table table-sm table-bordered">
        <thead>
            <tr>
                <th>Cód. Fábrica</th>
                <th>Nombre</th>
                <th>Descripción</th>
                <th>Tipo</th>
                <th>Trazabilidad</th>
                <th>División</th>
                <th>Unidad</th>
                <th>Plus</th>
                <th>Cód. Ext.</th>
                <th>Errores</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in PreviewItems)
            {
                <tr class="@(item.HasError ? "table-danger" : null)">
                    <td>@item.FactoryCode</td>
                    <td>@item.Name</td>
                    <td>@item.Description</td>
                    <td>@item.ProductType</td>
                    <td>@item.TraceabilityType</td>
                    <td>@item.DivisionCode</td>
                    <td>@item.UnitCode</td>
                    <td>@(item.PlusProcess ? "Sí" : "No")</td>
                    <td>@item.ExternalCode</td>
                    <td>@item.ErrorMessage</td>
                </tr>
            }
        </tbody>
    </table>

    <div class="mt-3 d-flex justify-content-end">
        <button class="btn btn-success" @onclick="ConfirmImport" disabled="@(PreviewItems.Any(x => x.HasError))">
            Importar productos
        </button>
    </div>
}

@code {
    private List<ProductImportPreviewDto>? PreviewItems;
    private IBrowserFile? UploadedFile;
    private bool _isUploading;

    private async Task DownloadTemplate()
    {
        try
        {
            await productService.DownloadTemplateAsync();
        }
        catch (Exception ex)
        {
            toastService.ShowError($"Error al descargar la plantilla: {ex.Message}");
        }
    }

    private void HandleFileSelected(InputFileChangeEventArgs e)
    {
        UploadedFile = e.File;
        PreviewItems = null; // limpiar vista previa anterior
    }

    private async Task ProcessFile()
    {
        if (UploadedFile == null) return;

        try
        {
            _isUploading = true;
            PreviewItems = await productService.PreviewImportAsync(UploadedFile);
            toastService.ShowSuccess("Vista previa generada correctamente.");
        }
        catch (Exception ex)
        {
            toastService.ShowError($"Error al procesar el archivo: {ex.Message}");
        }
        finally
        {
            _isUploading = false;
        }
    }

    private async Task ConfirmImport()
    {
        if (PreviewItems is null || PreviewItems.Any(x => x.HasError))
        {
            toastService.ShowWarning("Existen errores; corríjalos antes de importar.");
            return;
        }

        try
        {
            var result = await productService.ConfirmImportAsync(PreviewItems);
            toastService.ShowSuccess($"Se importaron {result?.Inserted ?? 0} productos.");
            UploadedFile = null;
            PreviewItems = null;
        }
        catch (Exception ex)
        {
            toastService.ShowError($"Error al importar: {ex.Message}");
        }
    }
}
