@*
    EN: Receipt — 80mm thermal printer receipt template with store info, items, totals.
    VI: Hóa đơn — Mẫu hóa đơn nhiệt 80mm với thông tin cửa hàng, sản phẩm, tổng tiền.
*@
@page "/pos/{ShopId:guid}/payment/receipt"
@page "/pos/{ShopId:guid}/payment/receipt/{OrderId:guid}"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject IJSRuntime JS
@inject PosDataService DataService

@if (_isLoading)
{
    <div style="display:flex;align-items:center;justify-content:center;height:100%;">
        <div style="text-align:center;">
            <div style="width:48px;height:48px;border:4px solid var(--pos-border-subtle);border-top-color:var(--pos-orange-primary);
                        border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 16px;"></div>
            <div style="color:var(--pos-text-tertiary);font-size:14px;">Đang tải hóa đơn...</div>
        </div>
    </div>
}
else
{
    <div style="display:flex;align-items:flex-start;justify-content:center;height:100%;padding:24px;overflow-y:auto;">
        @* ═══ RECEIPT PAPER ═══ *@
        <div id="receipt-content" style="width:100%;max-width:300px;background:#fff;color:#000;border-radius:4px;padding:24px 20px;font-family:'Courier New',monospace;">
            @* ═══ STORE HEADER ═══ *@
            <div style="text-align:center;margin-bottom:16px;">
                <div style="font-size:18px;font-weight:700;">@_shopName</div>
                <div style="font-size:11px;margin-top:4px;">@_shopAddress</div>
            </div>

            @* EN: Dashed separator / VI: Đường kẻ đứt *@
            <div style="border-top:1px dashed #000;margin:12px 0;"></div>

            @* ═══ ORDER INFO ═══ *@
            <div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:8px;">
                <span>Đơn #@_orderNumber</span>
                <span>@_orderDate</span>
            </div>
            <div style="font-size:11px;margin-bottom:4px;">NV: @StaffName</div>

            <div style="border-top:1px dashed #000;margin:12px 0;"></div>

            @* ═══ ITEM LIST ═══ *@
            @foreach (var item in _items)
            {
                <div style="display:flex;justify-content:space-between;font-size:12px;padding:3px 0;">
                    <span>@item.Quantity x @item.ProductName</span>
                    <span>@FormatPrice(item.Subtotal)</span>
                </div>
            }

            <div style="border-top:1px dashed #000;margin:12px 0;"></div>

            @* ═══ TOTALS ═══ *@
            <div style="display:flex;flex-direction:column;gap:4px;font-size:12px;">
                <div style="display:flex;justify-content:space-between;">
                    <span>Tạm tính</span>
                    <span>@FormatPrice(_subtotal)</span>
                </div>
                @if (_serviceCharge > 0)
                {
                    <div style="display:flex;justify-content:space-between;">
                        <span>Phí dịch vụ</span>
                        <span>@FormatPrice(_serviceCharge)</span>
                    </div>
                }
                @if (_vat > 0)
                {
                    <div style="display:flex;justify-content:space-between;">
                        <span>VAT</span>
                        <span>@FormatPrice(_vat)</span>
                    </div>
                }
            </div>

            <div style="border-top:2px solid #000;margin:10px 0;"></div>

            <div style="display:flex;justify-content:space-between;font-size:16px;font-weight:700;">
                <span>TỔNG CỘNG</span>
                <span>@FormatPrice(_total)</span>
            </div>

            <div style="border-top:1px dashed #000;margin:12px 0;"></div>

            @* ═══ PAYMENT INFO ═══ *@
            <div style="display:flex;flex-direction:column;gap:4px;font-size:12px;">
                <div style="display:flex;justify-content:space-between;">
                    <span>Thanh toán</span>
                    <span>@_paymentMethodDisplay</span>
                </div>
            </div>

            <div style="border-top:1px dashed #000;margin:12px 0;"></div>

            @* ═══ TRANSACTION ID ═══ *@
            <div style="text-align:center;font-size:11px;color:#666;">
                <div>Mã đơn: @_orderNumber</div>
                <div>@_orderDate @_orderTime</div>
            </div>

            <div style="border-top:1px dashed #000;margin:12px 0;"></div>

            @* ═══ FOOTER ═══ *@
            <div style="text-align:center;font-size:13px;font-weight:700;margin-top:8px;">
                Cảm ơn quý khách!
            </div>
            <div style="text-align:center;font-size:10px;color:#666;margin-top:4px;">
                Thank you & see you again!
            </div>
        </div>
    </div>
}

@* ═══ ACTION BUTTONS (fixed bottom) ═══ *@
<div style="position:fixed;bottom:0;left:0;right:0;padding:16px;display:flex;justify-content:center;gap:12px;background:var(--pos-bg-elevated);border-top:1px solid var(--pos-border-subtle);">
    <button style="display:flex;align-items:center;gap:8px;padding:12px 28px;border-radius:var(--pos-radius);border:none;
                   background:var(--pos-orange-primary);color:#fff;cursor:pointer;font-size:14px;font-weight:600;"
            @onclick="Print">
        <i data-lucide="printer" style="width:16px;height:16px;"></i>
        In hóa đơn
    </button>
    <button style="padding:12px 24px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                   background:transparent;color:var(--pos-text-secondary);cursor:pointer;font-size:14px;"
            @onclick="Close">
        Đóng
    </button>
</div>

<style>
    @@keyframes spin { to { transform: rotate(360deg); } }
</style>

@code {
    // EN: OrderId from route parameter or query string.
    // VI: OrderId từ route parameter hoặc query string.
    [Parameter] public Guid? OrderId { get; set; }
    [SupplyParameterFromQuery(Name = "orderId")] public Guid? OrderIdQuery { get; set; }

    private Guid _resolvedOrderId => OrderId ?? OrderIdQuery ?? Guid.Empty;

    private bool _isLoading = true;

    // EN: Receipt data populated from API.
    // VI: Dữ liệu hóa đơn được điền từ API.
    private string _shopName = "GOODGO";
    private string _shopAddress = "";
    private string _orderNumber = "";
    private string _orderDate = "";
    private string _orderTime = "";
    private List<PosDataService.OrderItemInfo> _items = new();
    private decimal _subtotal;
    private decimal _serviceCharge;
    private decimal _vat;
    private decimal _total;
    private string _paymentMethodDisplay = "";

    private static readonly Dictionary<string, string> _methodNames = new()
    {
        ["cash"] = "Tiền mặt",
        ["card"] = "Thẻ",
        ["qr"] = "Mã QR",
        ["transfer"] = "Chuyển khoản",
    };

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await LoadReceiptAsync();
    }

    private async Task LoadReceiptAsync()
    {
        _isLoading = true;
        try
        {
            if (_resolvedOrderId == Guid.Empty) { _isLoading = false; return; }
            var detail = await DataService.GetOrderDetailAsync(_resolvedOrderId, ShopId);
            if (detail?.Order != null)
            {
                _orderNumber = _resolvedOrderId.ToString("N")[..8].ToUpper();
                _orderDate = detail.Order.CreatedAt.ToString("dd/MM/yyyy");
                _orderTime = detail.Order.CreatedAt.ToString("HH:mm:ss");
                _total = detail.Order.TotalAmount;

                if (!string.IsNullOrEmpty(detail.Order.PaymentMethod))
                {
                    _paymentMethodDisplay = _methodNames.TryGetValue(detail.Order.PaymentMethod, out var n)
                        ? n : detail.Order.PaymentMethod;
                }
            }
            if (detail?.Items != null)
            {
                _items = detail.Items;
                _subtotal = _items.Sum(i => i.Subtotal);
                // EN: Calculate tax/service from difference between total and subtotal.
                // VI: Tính thuế/phí dịch vụ từ chênh lệch giữa tổng và tạm tính.
                var diff = _total - _subtotal;
                if (diff > 0)
                {
                    _serviceCharge = Math.Round(diff * 0.385m); // ~5/13 of diff
                    _vat = diff - _serviceCharge;
                }
            }
            if (!string.IsNullOrEmpty(StoreName))
                _shopName = StoreName;
        }
        catch { /* graceful — show partial data */ }
        finally { _isLoading = false; }
    }

    private async Task Print()
    {
        // EN: Trigger browser print dialog / VI: Kích hoạt hộp thoại in từ trình duyệt
        await JS.InvokeVoidAsync("window.print");
    }

    private void Close()
    {
        NavigationManager.NavigateTo($"/pos/{ShopId}/payment/success?orderId={_resolvedOrderId}");
    }
}
