@*
    EN: QR Payment — QR code display with provider tabs, timer countdown.
    VI: Thanh toán QR — Hiển thị mã QR với tab nhà cung cấp, đếm ngược.
*@
@page "/pos/{ShopId:guid}/payment/qr"
@page "/pos/{ShopId:guid}/payment/qr/{OrderId:guid}"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@implements IDisposable

@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 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:24px;">
        @* ═══ 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>

        @* ═══ QR PROVIDER TABS ═══ *@
        <div style="display:flex;gap:8px;background:var(--pos-bg-elevated);padding:4px;border-radius:var(--pos-radius);">
            @foreach (var provider in _providers)
            {
                <button style="padding:10px 20px;border-radius:8px;border:none;cursor:pointer;font-size:13px;font-weight:600;
                               background:@(_selectedProvider == provider ? "var(--pos-orange-primary)" : "transparent");
                               color:@(_selectedProvider == provider ? "#fff" : "var(--pos-text-secondary)");"
                        @onclick="() => _selectedProvider = provider">
                    @provider
                </button>
            }
        </div>

        @* ═══ QR CODE DISPLAY ═══ *@
        <div style="width:240px;height:240px;background:var(--pos-bg-elevated);border-radius:16px;border:2px solid var(--pos-border-default);
                    display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;">
            <i data-lucide="qr-code" style="width:100px;height:100px;color:var(--pos-text-primary);"></i>
            <span style="font-size:12px;color:var(--pos-text-tertiary);">@_selectedProvider</span>
        </div>

        @* ═══ TIMER ═══ *@
        <div style="display:flex;align-items:center;gap:8px;color:var(--pos-warning);font-size:15px;">
            <i data-lucide="clock" style="width:16px;height:16px;"></i>
            <span style="font-weight:600;">@_timerDisplay</span>
        </div>

        @* ═══ STATUS ═══ *@
        @if (_isProcessing)
        {
            <div style="display:flex;align-items:center;gap:8px;color:var(--pos-text-tertiary);font-size:14px;">
                <div style="width:8px;height:8px;border-radius:50%;background:var(--pos-orange-primary);animation:pulse 2s ease-in-out infinite;"></div>
                Đang xử lý thanh toán...
            </div>
        }
        else if (_timerSeconds > 0)
        {
            <div style="display:flex;align-items:center;gap:8px;color:var(--pos-text-tertiary);font-size:14px;">
                <div style="width:8px;height:8px;border-radius:50%;background:var(--pos-warning);animation:pulse 2s ease-in-out infinite;"></div>
                Chờ xác nhận thanh toán...
            </div>
        }
        else
        {
            <div style="display:flex;align-items:center;gap:8px;color:var(--pos-danger);font-size:14px;font-weight:600;">
                <div style="width:8px;height:8px;border-radius:50%;background:var(--pos-danger);"></div>
                Mã QR đã hết hạn. Nhấn "Làm mới" để tạo mã mới.
            </div>
        }

        @* ═══ ACTIONS ═══ *@
        <div style="display:flex;gap:12px;">
            <button style="display:flex;align-items:center;gap:6px;padding:10px 20px;border-radius:var(--pos-radius);border:none;
                           background:var(--pos-orange-primary);color:#fff;cursor:pointer;font-size:13px;font-weight:600;"
                    disabled="@(_isProcessing)"
                    @onclick="ConfirmPayment">
                Xác nhận thanh toán
            </button>
            <button style="display:flex;align-items:center;gap:6px;padding:10px 20px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                           background:var(--pos-bg-elevated);color:var(--pos-text-secondary);cursor:pointer;font-size:13px;"
                    @onclick="Refresh">
                <i data-lucide="refresh-cw" style="width:14px;height:14px;"></i> Làm mới
            </button>
            <button style="padding:10px 20px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                           background:transparent;color:var(--pos-text-secondary);cursor:pointer;font-size:13px;"
                    @onclick="Cancel">
                Hủy
            </button>
        </div>
    </div>
}

<style>
    @@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
    @@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 decimal _orderTotal;
    private string _selectedProvider = "VietQR";
    private int _timerSeconds = 300;
    private string _timerDisplay => $"{_timerSeconds / 60}:{(_timerSeconds % 60):D2}";
    private Timer? _countdownTimer;
    private bool _isLoading = true;
    private bool _isProcessing;
    private string? _errorMessage;
    private bool _disposed = false;

    // EN: QR providers / VI: Nhà cung cấp QR
    private readonly string[] _providers = { "VietQR", "MoMo", "ZaloPay" };

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

    private async Task LoadOrderAsync()
    {
        _isLoading = 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 { _isLoading = false; }
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender && !_isLoading && _errorMessage == null)
        {
            _countdownTimer = new Timer(_ =>
            {
                if (!_disposed && _timerSeconds > 0)
                {
                    _timerSeconds--;
                    InvokeAsync(StateHasChanged);
                }
            }, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
        }
    }

    private async Task ConfirmPayment()
    {
        _isProcessing = true;
        StateHasChanged();
        try
        {
            // EN: Map QR provider to gateway name for online payment flow.
            // VI: Map nhà cung cấp QR sang tên gateway cho thanh toán trực tuyến.
            var gateway = _selectedProvider.ToLowerInvariant() switch
            {
                "momo" => "momo",
                "zalopay" => "vnpay",   // EN: ZaloPay routes through VNPay gateway / VI: ZaloPay đi qua cổng VNPay
                _ => "qr"               // EN: VietQR — POS-confirmed, no redirect / VI: VietQR — POS xác nhận, không redirect
            };

            var returnUrl = $"{NavigationManager.BaseUri}pos/{ShopId}/payment/success?orderId={_resolvedOrderId}&method=qr";
            var result = await DataService.PayOrderWithDetailsAsync(
                _resolvedOrderId, ShopId, gateway, returnUrl: returnUrl);

            if (result?.Success == true)
            {
                // EN: If payment URL returned (online gateway), redirect to payment page.
                // VI: Nếu có URL thanh toán (cổng trực tuyến), redirect đến trang thanh toán.
                if (!string.IsNullOrEmpty(result.PaymentUrl))
                {
                    NavigationManager.NavigateTo(result.PaymentUrl, forceLoad: true);
                }
                else
                {
                    NavigationManager.NavigateTo($"/pos/{ShopId}/payment/success?orderId={_resolvedOrderId}&method=qr");
                }
            }
            else
            {
                _errorMessage = result?.ErrorMessage ?? "Thanh toán 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 Refresh()
    {
        _timerSeconds = 300;
        _errorMessage = null;
    }

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

    public void Dispose()
    {
        _disposed = true;
        _countdownTimer?.Dispose();
    }
}
