@*
    EN: Payment Method Select — Choose payment method: Cash, Card, QR Code, Bank Transfer.
    VI: Chọn phương thức thanh toán — Tiền mặt, Thẻ, Mã QR, Chuyển khoản.
*@
@page "/pos/{ShopId:guid}/payment/method-select"
@page "/pos/{ShopId:guid}/payment-method-select/{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 đơn hàng...</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="GoBack">
            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:8px;">Tổng đơn hàng / Order Total</div>
            <div style="font-size:36px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(_orderTotal)</div>
        </div>

        @* ═══ PAYMENT METHODS ═══ *@
        <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:16px;width:100%;max-width:520px;">
            @foreach (var method in _methods)
            {
                <button style="display:flex;flex-direction:column;align-items:center;gap:12px;padding:32px 16px;border-radius:var(--pos-radius);
                               border:2px solid var(--pos-border-default);background:var(--pos-bg-elevated);color:var(--pos-text-primary);cursor:pointer;
                               transition:border-color 0.2s;"
                        @onclick="() => SelectMethod(method.Route)">
                    <span style="font-size:40px;">@method.Icon</span>
                    <span style="font-size:16px;font-weight:600;">@method.Label</span>
                    <span style="font-size:12px;color:var(--pos-text-tertiary);text-align:center;">@method.Description</span>
                </button>
            }
        </div>

        @* ═══ CANCEL & BACK BUTTONS ═══ *@
        <div style="display:flex;gap:12px;">
            <button style="display:flex;align-items:center;gap:8px;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="GoBack">
                <i data-lucide="arrow-left" style="width:16px;height:16px;"></i>
                Quay lại
            </button>
            <button style="display:flex;align-items:center;gap:8px;padding:12px 24px;border-radius:var(--pos-radius);border:1px solid var(--pos-danger);
                           background:transparent;color:var(--pos-danger);cursor:pointer;font-size:14px;"
                    disabled="@_isCancelling"
                    @onclick="CancelOrder">
                <i data-lucide="x" style="width:16px;height:16px;"></i>
                @(_isCancelling ? "Đang hủy..." : "Hủy đơn")
            </button>
        </div>
    </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 decimal _orderTotal;
    private bool _isLoading = true;
    private bool _isCancelling;
    private string? _errorMessage;

    // EN: Payment method definitions / VI: Định nghĩa phương thức thanh toán
    private readonly List<PaymentMethod> _methods = new()
    {
        new("💵", "Tiền mặt", "Thanh toán bằng tiền mặt", "payment/cash"),
        new("💳", "Thẻ", "Chạm, quẹt hoặc cắm thẻ", "payment/card"),
        new("📱", "Mã QR", "VietQR, MoMo, ZaloPay", "payment/qr"),
        new("🏦", "Chuyển khoản", "Chuyển khoản ngân hàng", "payment/bank-transfer"),
    };

    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;
        }
    }

    private void SelectMethod(string route)
    {
        NavigationManager.NavigateTo($"/pos/{ShopId}/{route}?orderId={_resolvedOrderId}");
    }

    private async Task CancelOrder()
    {
        _isCancelling = true;
        StateHasChanged();
        try
        {
            await DataService.CancelOrderAsync(_resolvedOrderId);
        }
        finally
        {
            _isCancelling = false;
        }
        await JS.InvokeVoidAsync("history.back");
    }

    private async Task GoBack() => await JS.InvokeVoidAsync("history.back");

    private record PaymentMethod(string Icon, string Label, string Description, string Route);
}
