@*
    EN: Cash Payment — Cash payment with quick amount buttons and change calculation.
    VI: Thanh toán tiền mặt — Nút số tiền nhanh và tính tiền thối.
*@
@page "/pos/{ShopId:guid}/payment/cash"
@page "/pos/{ShopId:guid}/payment/cash/{OrderId:guid}"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@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 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;height:100%;">
        @* ═══ MAIN PANEL ═══ *@
        <div style="flex:1;padding:32px;display:flex;flex-direction:column;align-items:center;gap:24px;overflow-y:auto;">
            @* ═══ 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>

            @* ═══ QUICK AMOUNT BUTTONS ═══ *@
            <div style="width:100%;max-width:480px;">
                <div style="font-size:14px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:12px;">Số tiền nhanh</div>
                <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;">
                    @foreach (var amount in _quickAmounts)
                    {
                        <button style="padding:16px;border-radius:var(--pos-radius);border:2px solid @(_receivedAmount == amount.Value ? "var(--pos-orange-primary)" : "var(--pos-border-default)");
                                       background:@(_receivedAmount == amount.Value ? "rgba(255,92,0,0.1)" : "var(--pos-bg-elevated)");
                                       color:var(--pos-text-primary);cursor:pointer;font-size:15px;font-weight:600;text-align:center;"
                                @onclick="() => SetAmount(amount.Value)">
                            @amount.Label
                        </button>
                    }
                </div>
            </div>

            @* ═══ CUSTOM AMOUNT INPUT ═══ *@
            <div style="width:100%;max-width:480px;">
                <div style="font-size:14px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:8px;">Nhập số tiền khác</div>
                <div style="display:flex;align-items:center;gap:8px;">
                    <input type="number" @bind="_customInput" @bind:event="oninput"
                           placeholder="Nhập số tiền..."
                           style="flex:1;padding:14px 16px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                                  background:var(--pos-bg-elevated);color:var(--pos-text-primary);font-size:16px;outline:none;" />
                    <button style="padding:14px 20px;border-radius:var(--pos-radius);border:none;background:var(--pos-bg-interactive);
                                   color:var(--pos-text-primary);cursor:pointer;font-size:14px;font-weight:600;"
                            @onclick="ApplyCustom">
                        Áp dụng
                    </button>
                </div>
            </div>

            @* ═══ CHANGE DISPLAY ═══ *@
            <div style="width:100%;max-width:480px;background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;">
                <div style="display:flex;justify-content:space-between;margin-bottom:12px;">
                    <span style="color:var(--pos-text-secondary);font-size:14px;">Khách đưa</span>
                    <span style="font-size:16px;font-weight:600;">@FormatPrice(_receivedAmount)</span>
                </div>
                <div style="display:flex;justify-content:space-between;padding-top:12px;border-top:1px dashed var(--pos-border-subtle);">
                    <span style="color:var(--pos-text-secondary);font-size:14px;">Tiền thối</span>
                    <span style="font-size:20px;font-weight:700;color:@(_changeAmount >= 0 ? "var(--pos-success)" : "var(--pos-danger)");">
                        @FormatPrice(_changeAmount)
                    </span>
                </div>
            </div>
        </div>

        @* ═══ CONFIRM PANEL ═══ *@
        <div style="width:280px;background:var(--pos-bg-elevated);border-left:1px solid var(--pos-border-subtle);padding:24px;display:flex;flex-direction:column;justify-content:flex-end;gap:12px;">
            <button style="padding:8px 16px;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:14px;height:14px;"></i> Quay lại
            </button>
            <button class="pos-btn-checkout" @onclick="Confirm"
                    disabled="@(_receivedAmount < _orderTotal || _isProcessing)">
                @if (_isProcessing)
                {
                    <span>Đang xử lý...</span>
                }
                else
                {
                    <span>Xác nhận thanh toán</span>
                }
            </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 decimal _receivedAmount = 0;
    private decimal _changeAmount => _receivedAmount - _orderTotal;
    private string _customInput = "";
    private bool _isLoading = true;
    private bool _isProcessing;
    private string? _errorMessage;

    // EN: Quick amount options — dynamically generated based on order total.
    // VI: Tùy chọn số tiền nhanh — tự động sinh dựa trên tổng đơn hàng.
    private List<QuickAmount> _quickAmounts = new();

    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;
            BuildQuickAmounts();
        }
        catch { _errorMessage = "Lỗi khi tải đơn hàng. Vui lòng thử lại."; }
        finally { _isLoading = false; }
    }

    private void BuildQuickAmounts()
    {
        // EN: Generate sensible quick amounts based on order total.
        // VI: Sinh các mức tiền nhanh hợp lý dựa trên tổng đơn hàng.
        var rounded = Math.Ceiling(_orderTotal / 50_000) * 50_000;
        _quickAmounts = new()
        {
            new(FormatPrice(rounded), rounded),
            new(FormatPrice(rounded + 50_000), rounded + 50_000),
            new(FormatPrice(rounded + 100_000), rounded + 100_000),
            new(FormatPrice(rounded + 200_000), rounded + 200_000),
            new("1,000,000₫", 1_000_000),
            new("Đúng tiền", _orderTotal),
        };
    }

    private void SetAmount(decimal amount) => _receivedAmount = amount;

    private void ApplyCustom()
    {
        if (decimal.TryParse(_customInput, out var val))
            _receivedAmount = val;
    }

    private async Task Confirm()
    {
        _isProcessing = true;
        StateHasChanged();
        try
        {
            var result = await DataService.PayOrderWithDetailsAsync(
                _resolvedOrderId, ShopId, "cash", amountTendered: _receivedAmount);
            if (result?.Success == true)
            {
                var change = result.ChangeAmount ?? _changeAmount;
                NavigationManager.NavigateTo($"/pos/{ShopId}/payment/success?orderId={_resolvedOrderId}&method=cash&change={change}");
            }
            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 GoBack()
    {
        NavigationManager.NavigateTo($"/pos/{ShopId}/payment/method-select?orderId={_resolvedOrderId}");
    }

    private record QuickAmount(string Label, decimal Value);
}
