@*
    EN: Payment Success — Success animation, transaction details, print/new order buttons.
    VI: Thanh toán thành công — Hiệu ứng thành công, chi tiết giao dịch, nút in/đơn mới.
*@
@page "/pos/{ShopId:guid}/payment/success"
@page "/pos/{ShopId:guid}/payment/success/{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...</div>
        </div>
    </div>
}
else
{
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:32px;gap:24px;">
        @* ═══ SUCCESS ANIMATION ═══ *@
        <div style="width:100px;height:100px;border-radius:50%;background:rgba(34,197,94,0.15);display:flex;align-items:center;justify-content:center;
                    animation:scaleIn 0.5s ease-out;">
            <div style="width:72px;height:72px;border-radius:50%;background:var(--pos-success);display:flex;align-items:center;justify-content:center;">
                <i data-lucide="check" style="width:36px;height:36px;color:#fff;stroke-width:3;"></i>
            </div>
        </div>

        @* ═══ SUCCESS MESSAGE ═══ *@
        <div style="text-align:center;">
            <div style="font-size:24px;font-weight:700;color:var(--pos-success);margin-bottom:8px;">Thanh toán thành công!</div>
            <div style="font-size:14px;color:var(--pos-text-tertiary);">Payment successful</div>
        </div>

        @* ═══ TRANSACTION DETAILS ═══ *@
        <div style="width:100%;max-width:400px;background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;display:flex;flex-direction:column;gap:12px;">
            <div style="display:flex;justify-content:space-between;font-size:14px;">
                <span style="color:var(--pos-text-tertiary);">Tổng thanh toán</span>
                <span style="font-weight:700;color:var(--pos-orange-primary);font-size:18px;">@FormatPrice(_orderTotal)</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:14px;">
                <span style="color:var(--pos-text-tertiary);">Phương thức</span>
                <span style="font-weight:600;">@_paymentMethodDisplay</span>
            </div>
            @if (_changeAmount > 0)
            {
                <div style="display:flex;justify-content:space-between;font-size:14px;">
                    <span style="color:var(--pos-text-tertiary);">Tiền thối</span>
                    <span style="font-weight:600;color:var(--pos-success);">@FormatPrice(_changeAmount)</span>
                </div>
            }
            @if (_orderItems.Any())
            {
                <div style="padding-top:12px;border-top:1px solid var(--pos-border-subtle);">
                    <div style="font-size:13px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:8px;">Chi tiết đơn hàng</div>
                    @foreach (var item in _orderItems)
                    {
                        <div style="display:flex;justify-content:space-between;font-size:13px;padding:4px 0;">
                            <span style="color:var(--pos-text-secondary);">@item.Quantity x @item.ProductName</span>
                            <span style="font-weight:500;">@FormatPrice(item.Subtotal)</span>
                        </div>
                    }
                </div>
            }
            <div style="display:flex;justify-content:space-between;font-size:14px;padding-top:12px;border-top:1px solid var(--pos-border-subtle);">
                <span style="color:var(--pos-text-tertiary);">Mã đơn hàng</span>
                <span style="font-weight:500;color:var(--pos-text-secondary);font-size:12px;">@_resolvedOrderId.ToString("N")[..8].ToUpper()</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:14px;">
                <span style="color:var(--pos-text-tertiary);">Thời gian</span>
                <span style="font-weight:500;color:var(--pos-text-secondary);font-size:12px;">@_orderTime.ToString("dd/MM/yyyy HH:mm:ss")</span>
            </div>
        </div>

        @* ═══ ACTION BUTTONS ═══ *@
        <div style="display:flex;gap:12px;">
            <button style="display:flex;align-items:center;gap:8px;padding:14px 28px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                           background:var(--pos-bg-elevated);color:var(--pos-text-primary);cursor:pointer;font-size:14px;font-weight:600;"
                    @onclick="PrintReceipt">
                <i data-lucide="printer" style="width:18px;height:18px;"></i>
                In hóa đơn
            </button>
            <button style="display:flex;align-items:center;gap:8px;padding:14px 28px;border-radius:var(--pos-radius);border:none;
                           background:var(--pos-orange-primary);color:#fff;cursor:pointer;font-size:14px;font-weight:600;"
                    @onclick="NewOrder">
                <i data-lucide="plus" style="width:18px;height:18px;"></i>
                Đơn mới
            </button>
        </div>
    </div>
}

<style>
    @@keyframes scaleIn {
        from { transform: scale(0); opacity: 0; }
        to { transform: scale(1); opacity: 1; }
    }
    @@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; }
    [SupplyParameterFromQuery(Name = "method")] public string? MethodQuery { get; set; }
    [SupplyParameterFromQuery(Name = "change")] public string? ChangeQuery { get; set; }

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

    private decimal _orderTotal;
    private string _paymentMethodDisplay = "";
    private decimal _changeAmount;
    private DateTime _orderTime = DateTime.Now;
    private List<PosDataService.OrderItemInfo> _orderItems = new();
    private bool _isLoading = true;

    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 LoadOrderAsync();
    }

    private async Task LoadOrderAsync()
    {
        _isLoading = true;
        try
        {
            // EN: Parse change amount from query string if present (for cash payments).
            // VI: Phân tích số tiền thối từ query string nếu có (cho thanh toán tiền mặt).
            if (decimal.TryParse(ChangeQuery, out var change))
                _changeAmount = change;

            // EN: Resolve payment method display name.
            // VI: Xác định tên hiển thị phương thức thanh toán.
            _paymentMethodDisplay = MethodQuery != null && _methodNames.TryGetValue(MethodQuery, out var name)
                ? name : "Không xác định";

            if (_resolvedOrderId != Guid.Empty)
            {
                var detail = await DataService.GetOrderDetailAsync(_resolvedOrderId, ShopId);
                if (detail?.Order != null)
                {
                    _orderTotal = detail.Order.TotalAmount;
                    _orderTime = detail.Order.CreatedAt;
                    if (!string.IsNullOrEmpty(detail.Order.PaymentMethod))
                    {
                        _paymentMethodDisplay = _methodNames.TryGetValue(detail.Order.PaymentMethod, out var n)
                            ? n : detail.Order.PaymentMethod;
                    }
                }
                if (detail?.Items != null)
                    _orderItems = detail.Items;
            }
        }
        catch { /* graceful — show what we have from query params */ }
        finally { _isLoading = false; }
    }

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

    private void NewOrder()
    {
        // EN: Navigate back to the main POS page for this shop.
        // VI: Điều hướng về trang POS chính của shop.
        NavigationManager.NavigateTo($"/pos/{ShopId}");
    }
}
