@using Domain.Dtos.Sales

@if (Visible && Summary != null)
{
    <div class="position-fixed top-0 start-0 w-100 h-100"
         style="background: rgba(0,0,0,0.4); z-index: 1040;"
         @onclick="Close">
    </div>

    <div class="position-fixed top-0 end-0 h-100 bg-white shadow"
         style="width: 45%; z-index: 1050; overflow-y: auto;">
        <div class="d-flex justify-content-between align-items-center border-bottom px-3 py-2">
            <div>
                <h5 class="m-0">Detalle Remito @HeaderNumber</h5>
                <div class="mt-1">
                    <span class="badge @GetStatusBadge(HeaderStatus)">@HeaderStatus</span>
                </div>
            </div>
            <button type="button" class="btn-close" @onclick="Close"></button>
        </div>

        <div class="p-3" style="zoom: 0.8;">
            <ul class="nav nav-tabs mb-3" role="tablist">
                <li class="nav-item">
                    <button type="button"
                            class="nav-link @((activeTab == "Datos") ? "active bg-primary text-white" : "")"
                            @onclick='() => activeTab = "Datos"'
                            title="Datos generales">
                        <i class="fas fa-info-circle me-1"></i> Datos
                    </button>
                </li>
                <li class="nav-item">
                    <button type="button"
                            class="nav-link @((activeTab == "Items") ? "active bg-success text-white" : "")"
                            @onclick='() => activeTab = "Items"'
                            title="Detalle de líneas">
                        <i class="fas fa-boxes-stacked me-1"></i> Items
                    </button>
                </li>
            </ul>

            @if (Loading)
            {
                <div class="text-center text-muted py-4">Cargando detalle...</div>
            }
            else if (activeTab == "Datos")
            {
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-semibold mb-1">Remito</label>
                        <div class="form-control form-control-sm bg-light">@HeaderNumber</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-semibold mb-1">Fecha de emisión</label>
                        <div class="form-control form-control-sm bg-light">@HeaderIssueDate.ToString("dd/MM/yyyy")</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-semibold mb-1">Cliente</label>
                        <div class="form-control form-control-sm bg-light">@HeaderCustomerName</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-semibold mb-1">Presupuesto relacionado</label>
                        <div class="form-control form-control-sm bg-light">@HeaderQuoteNumber</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-semibold mb-1">Estado</label>
                        <div><span class="badge @GetStatusBadge(HeaderStatus)">@HeaderStatus</span></div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-semibold mb-1">Reimpresiones</label>
                        <div class="form-control form-control-sm bg-light">@HeaderPrintCount</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-semibold mb-1">Factura asociada</label>
                        <div class="form-control form-control-sm bg-light">@(Detail?.SalesInvoiceId?.ToString() ?? "—")</div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-semibold mb-1">Última modificación</label>
                        <div class="form-control form-control-sm bg-light">@(Detail?.ModifiedAt?.ToString("dd/MM/yyyy HH:mm") ?? "—")</div>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold mb-1">Observaciones</label>
                        <div class="form-control form-control-sm bg-light" style="min-height: 90px; white-space: pre-wrap;">@(string.IsNullOrWhiteSpace(Detail?.Observations) ? "—" : Detail!.Observations)</div>
                    </div>
                </div>
            }
            else
            {
                @if (Detail?.Items == null || !Detail.Items.Any())
                {
                    <p class="text-muted mb-0">No hay ítems para este remito.</p>
                }
                else
                {
                    <div class="table-responsive">
                        <table class="table table-sm align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th style="width: 80px;">Línea</th>
                                    <th>Descripción</th>
                                    <th style="width: 100px;">Cantidad</th>
                                    <th style="width: 120px;">Origen</th>
                                    <th>Notas</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var item in Detail.Items.OrderBy(i => i.LineNumber))
                                {
                                    <tr>
                                        <td class="text-center">@item.LineNumber</td>
                                        <td>@item.Description</td>
                                        <td class="text-center">@item.Quantity</td>
                                        <td>@GetOriginLabel(item.OriginType)</td>
                                        <td>@(string.IsNullOrWhiteSpace(item.Notes) ? "—" : item.Notes)</td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
                }
            }
        </div>
    </div>
}

@code {
    [Parameter] public bool Visible { get; set; }
    [Parameter] public EventCallback<bool> VisibleChanged { get; set; }
    [Parameter] public DeliveryNoteSummaryDto? Summary { get; set; }
    [Parameter] public DeliveryNoteDto? Detail { get; set; }
    [Parameter] public bool Loading { get; set; }

    private string activeTab = "Datos";
    private int? lastDeliveryNoteId;

    private string HeaderNumber => Detail?.DeliveryNoteNumber ?? Summary?.DeliveryNoteNumber ?? "—";
    private string HeaderStatus => Detail?.Status ?? Summary?.Status ?? "—";
    private DateTime HeaderIssueDate => Detail?.IssueDate ?? Summary?.IssueDate ?? DateTime.MinValue;
    private string HeaderCustomerName => string.IsNullOrWhiteSpace(Summary?.CustomerName) ? "—" : Summary!.CustomerName;
    private string HeaderQuoteNumber => string.IsNullOrWhiteSpace(Summary?.QuoteNumber) ? "—" : Summary!.QuoteNumber!;
    private int HeaderPrintCount => Detail?.PrintCount ?? Summary?.PrintCount ?? 0;

    protected override void OnParametersSet()
    {
        if (Summary?.Id != lastDeliveryNoteId)
        {
            activeTab = "Datos";
            lastDeliveryNoteId = Summary?.Id;
        }
    }

    private async Task Close()
    {
        await VisibleChanged.InvokeAsync(false);
    }

    private string GetStatusBadge(string status) => status switch
    {
        "Anulado" => "bg-danger text-white",
        "Emitido" => "bg-primary text-white",
        "Aprobado" => "bg-success",
        "Cerrado" => "bg-dark text-white",
        _ => "bg-light text-dark"
    };

    private string GetOriginLabel(byte originType) => originType switch
    {
        1 => "Presupuesto",
        2 => "Manual",
        _ => originType.ToString()
    };
}
