@*
    EN: Card Payment — Card reader status, tap/swipe/insert instructions.
    VI: Thanh toán thẻ — Trạng thái đầu đọc thẻ, hướng dẫn chạm/quẹt/cắm.
*@
@page "/pos/{ShopId:guid}/payment/card"
@page "/pos/{ShopId:guid}/payment/card/{OrderId:guid}"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService

@if (_isLoadingOrder)
{
    <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 if (!string.IsNullOrEmpty(_errorMessage))
{
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:16px;">
        <div style="color:var(--pos-danger);font-size:16px;font-weight:600;">@_errorMessage</div>
        <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="Cancel">Quay lại</button>
    </div>
}
else
{
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:32px;gap:32px;">
        @* ═══ ORDER TOTAL ═══ *@
        <div style="text-align:center;">
            <div style="font-size:14px;color:var(--pos-text-tertiary);margin-bottom:4px;">Tổng thanh toán</div>
            <div style="font-size:32px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(_orderTotal)</div>
        </div>

        @* ═══ CARD READER STATUS ═══ *@
        <div style="display:flex;flex-direction:column;align-items:center;gap:20px;padding:40px;background:var(--pos-bg-elevated);border-radius:16px;width:100%;max-width:400px;">
            @if (_isProcessing)
            {
                @* EN: Processing animation / VI: Hiệu ứng đang xử lý *@
                <div style="width:80px;height:80px;border-radius:50%;border:4px solid var(--pos-border-subtle);border-top-color:var(--pos-orange-primary);
                            animation:spin 1s linear infinite;"></div>
                <div style="font-size:18px;font-weight:600;color:var(--pos-text-primary);">Đang xử lý...</div>
                <div style="font-size:13px;color:var(--pos-text-tertiary);">Vui lòng không rút thẻ</div>
            }
            else
            {
                @* EN: Waiting for card / VI: Chờ thẻ *@
                <div style="width:80px;height:80px;border-radius:16px;background:var(--pos-bg-interactive);display:flex;align-items:center;justify-content:center;
                            animation:pulse 2s ease-in-out infinite;">
                    <i data-lucide="credit-card" style="width:40px;height:40px;color:var(--pos-orange-primary);"></i>
                </div>
                <div style="font-size:18px;font-weight:600;color:var(--pos-text-primary);">Chạm, quẹt hoặc cắm thẻ</div>
                <div style="font-size:13px;color:var(--pos-text-tertiary);">Tap, swipe or insert card</div>
            }
        </div>

        @* ═══ ACTIONS ═══ *@
        <div style="display:flex;gap:12px;">
            @if (!_isProcessing)
            {
                <button style="padding:12px 32px;border-radius:var(--pos-radius);border:none;background:var(--pos-orange-primary);color:#fff;
                               cursor:pointer;font-size:14px;font-weight:600;"
                        @onclick="ProcessCardPayment">
                    Xác nhận thanh toá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;"
                    disabled="@_isProcessing"
                    @onclick="Cancel">
                Hủy
            </button>
        </div>
    </div>
}

@* EN: CSS animations / VI: Hiệu ứng CSS *@
<style>
    @@keyframes spin { to { transform: rotate(360deg); } }
    @@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
</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 decimal _orderTotal;
    private bool _isLoadingOrder = true;
    private bool _isProcessing = false;
    private string? _errorMessage;

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

    private async Task LoadOrderAsync()
    {
        _isLoadingOrder = true;
        try
        {
            if (_resolvedOrderId == Guid.Empty) { _errorMessage = "Không tìm thấy mã đơn hàng."; return; }
            var detail = await DataService.GetOrderDetailAsync(_resolvedOrderId, ShopId);
            if (detail?.Order == null) { _errorMessage = "Không thể tải thông tin đơn hàng."; return; }
            _orderTotal = detail.Order.TotalAmount;
        }
        catch { _errorMessage = "Lỗi khi tải đơn hàng. Vui lòng thử lại."; }
        finally { _isLoadingOrder = false; }
    }

    private async Task ProcessCardPayment()
    {
        _isProcessing = true;
        StateHasChanged();
        try
        {
            var result = await DataService.PayOrderWithDetailsAsync(_resolvedOrderId, ShopId, "card");
            if (result?.Success == true)
            {
                NavigationManager.NavigateTo($"/pos/{ShopId}/payment/success?orderId={_resolvedOrderId}&method=card");
            }
            else
            {
                _errorMessage = result?.ErrorMessage ?? "Thanh toán thẻ thất bại. Vui lòng thử lại.";
            }
        }
        catch
        {
            _errorMessage = "Lỗi kết nối. Vui lòng thử lại.";
        }
        finally
        {
            _isProcessing = false;
        }
    }

    private void Cancel()
    {
        NavigationManager.NavigateTo($"/pos/{ShopId}/payment/method-select?orderId={_resolvedOrderId}");
    }
}
