@*
    EN: Tip Entry — Quick tip buttons, custom tip amount, total with tip display.
    VI: Nhập tiền tip — Nút tip nhanh, nhập số tiền tùy chỉnh, hiển thị tổng kèm tip.
*@
@page "/pos/{ShopId:guid}/payment/tip"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService

<div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:32px;gap:28px;">
    @* ═══ SUBTOTAL ═══ *@
    <div style="text-align:center;">
        <div style="font-size:14px;color:var(--pos-text-tertiary);margin-bottom:4px;">Tạm tính / Subtotal</div>
        <div style="font-size:28px;font-weight:700;color:var(--pos-text-primary);">@FormatPrice(_subtotal)</div>
    </div>

    @* ═══ QUICK TIP BUTTONS ═══ *@
    <div style="width:100%;max-width:480px;">
        <div style="font-size:14px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:12px;text-align:center;">Chọn mức tip</div>
        <div style="display:flex;gap:10px;">
            @foreach (var tip in _tipOptions)
            {
                <button style="flex:1;padding:16px 8px;border-radius:var(--pos-radius);
                               border:2px solid @(_selectedTip == tip.Label ? "var(--pos-orange-primary)" : "var(--pos-border-default)");
                               background:@(_selectedTip == tip.Label ? "rgba(255,92,0,0.1)" : "var(--pos-bg-elevated)");
                               color:var(--pos-text-primary);cursor:pointer;text-align:center;"
                        @onclick="() => SelectTip(tip)">
                    <div style="font-size:18px;font-weight:700;">@tip.Label</div>
                    @if (tip.Percent > 0)
                    {
                        <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:4px;">@FormatPrice(_subtotal * tip.Percent / 100)</div>
                    }
                </button>
            }
        </div>
    </div>

    @* ═══ CUSTOM TIP INPUT ═══ *@
    @if (_showCustomInput)
    {
        <div style="width:100%;max-width:480px;display:flex;gap:8px;">
            <input type="number" @bind="_customTipAmount" placeholder="Nhập số tiền tip..."
                   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-orange-primary);
                           color:#fff;cursor:pointer;font-size:14px;font-weight:600;"
                    @onclick="ApplyCustomTip">
                Áp dụng
            </button>
        </div>
    }

    @* ═══ TOTAL WITH TIP ═══ *@
    <div style="width:100%;max-width:480px;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ạm tính</span>
            <span>@FormatPrice(_subtotal)</span>
        </div>
        <div style="display:flex;justify-content:space-between;font-size:14px;">
            <span style="color:var(--pos-text-tertiary);">Tiền tip</span>
            <span style="color:var(--pos-success);font-weight:600;">+@FormatPrice(_tipAmount)</span>
        </div>
        <div style="display:flex;justify-content:space-between;font-size:20px;font-weight:700;padding-top:12px;border-top:1px dashed var(--pos-border-subtle);">
            <span>Tổng cộng</span>
            <span style="color:var(--pos-orange-primary);">@FormatPrice(_subtotal + _tipAmount)</span>
        </div>
    </div>

    @* ═══ ACTIONS ═══ *@
    <div style="display:flex;gap:12px;">
        <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="Skip">
            Bỏ qua
        </button>
        <button class="pos-btn-checkout" @onclick="Confirm">
            Xác nhận
        </button>
    </div>
</div>

@code {
    // EN: OrderId from route parameter or query string — passed from MethodSelect.
    // VI: OrderId từ route parameter hoặc query string — được truyền từ MethodSelect.
    [Parameter] public Guid? OrderId { get; set; }
    [SupplyParameterFromQuery(Name = "orderId")] public Guid? OrderIdQuery { get; set; }

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

    // EN: Subtotal loaded from Order Service API (FRONT-W-03).
    // VI: Tạm tính được tải từ Order Service API (FRONT-W-03).
    private decimal _subtotal = 0;
    private decimal _tipAmount = 0;
    private string _selectedTip = "";
    private bool _showCustomInput = false;
    private decimal _customTipAmount = 0;

    // EN: Tip options / VI: Tùy chọn tip
    private readonly List<TipOption> _tipOptions = new()
    {
        new("5%", 5),
        new("10%", 10),
        new("15%", 15),
        new("20%", 20),
        new("Khác", 0),
    };

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        if (_resolvedOrderId != Guid.Empty)
        {
            try
            {
                var detail = await DataService.GetOrderDetailAsync(_resolvedOrderId, ShopId);
                if (detail?.Order != null)
                    _subtotal = detail.Order.TotalAmount;
            }
            catch { /* EN: Non-critical — tip entry still usable with 0 subtotal / VI: Không quan trọng */ }
        }
    }

    private void SelectTip(TipOption tip)
    {
        _selectedTip = tip.Label;
        if (tip.Percent > 0)
        {
            _tipAmount = Math.Round(_subtotal * tip.Percent / 100);
            _showCustomInput = false;
        }
        else
        {
            _showCustomInput = true;
        }
    }

    private void ApplyCustomTip()
    {
        _tipAmount = _customTipAmount;
    }

    private void Skip() => NavigateTo($"payment/method-select?orderId={_resolvedOrderId}");
    private void Confirm() => NavigateTo($"payment/partial?orderId={_resolvedOrderId}");

    private record TipOption(string Label, decimal Percent);
}
