@*
    EN: Partial Payment — Split payment across multiple methods.
    VI: Thanh toán kết hợp — Chia thanh toán qua nhiều phương thức.
*@
@page "/pos/{ShopId:guid}/payment/partial"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService

<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 đơn hàng</div>
            <div style="font-size:32px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(_orderTotal)</div>
        </div>

        @* ═══ PAYMENT SPLITS ═══ *@
        <div style="width:100%;max-width:500px;display:flex;flex-direction:column;gap:12px;">
            <div style="font-size:14px;font-weight:600;color:var(--pos-text-secondary);">Phương thức thanh toán đã thêm</div>
            @foreach (var split in _splits)
            {
                <div style="display:flex;align-items:center;gap:12px;padding:16px;background:var(--pos-bg-elevated);border-radius:var(--pos-radius);">
                    <span style="font-size:24px;">@split.Icon</span>
                    <div style="flex:1;">
                        <div style="font-size:14px;font-weight:600;">@split.Method</div>
                        <div style="font-size:12px;color:var(--pos-text-tertiary);">@split.Description</div>
                    </div>
                    <span style="font-size:16px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(split.Amount)</span>
                    <button style="width:28px;height:28px;border-radius:6px;border:1px solid var(--pos-border-default);background:transparent;
                                   color:var(--pos-danger);cursor:pointer;display:flex;align-items:center;justify-content:center;"
                            @onclick="() => RemoveSplit(split)">
                        <i data-lucide="x" style="width:14px;height:14px;"></i>
                    </button>
                </div>
            }
        </div>

        @* ═══ ADD METHOD ═══ *@
        @if (_remainingBalance > 0)
        {
            <div style="width:100%;max-width:500px;">
                <div style="font-size:14px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:12px;">Thêm phương thức</div>
                <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:10px;">
                    @foreach (var option in _addOptions)
                    {
                        <button style="display:flex;align-items:center;gap:10px;padding:14px;border-radius:var(--pos-radius);
                                       border:1px dashed var(--pos-border-default);background:transparent;color:var(--pos-text-primary);
                                       cursor:pointer;font-size:14px;"
                                @onclick="() => AddSplit(option)">
                            <span style="font-size:20px;">@option.Icon</span>
                            @option.Label
                        </button>
                    }
                </div>
            </div>
        }
    </div>

    @* ═══ SUMMARY PANEL ═══ *@
    <div style="width:300px;background:var(--pos-bg-elevated);border-left:1px solid var(--pos-border-subtle);padding:24px;display:flex;flex-direction:column;">
        <div style="font-size:15px;font-weight:600;margin-bottom:20px;">Tóm tắt thanh toán</div>

        <div style="flex:1;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ổng đơn hàng</span>
                <span style="font-weight:600;">@FormatPrice(_orderTotal)</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:14px;">
                <span style="color:var(--pos-text-tertiary);">Đã thanh toán</span>
                <span style="font-weight:600;color:var(--pos-success);">@FormatPrice(_paidAmount)</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:14px;padding-top:12px;border-top:1px dashed var(--pos-border-subtle);">
                <span style="color:var(--pos-text-tertiary);">Còn lại</span>
                <span style="font-weight:700;font-size:18px;color:@(_remainingBalance > 0 ? "var(--pos-danger)" : "var(--pos-success)");">
                    @FormatPrice(_remainingBalance)
                </span>
            </div>

            @* EN: Progress bar / VI: Thanh tiến trình *@
            <div style="width:100%;height:6px;background:var(--pos-bg-interactive);border-radius:3px;overflow:hidden;">
                <div style="width:@(_progressPercent)%;height:100%;background:var(--pos-success);border-radius:3px;transition:width 0.3s;"></div>
            </div>
        </div>

        <div style="display:flex;flex-direction:column;gap:10px;margin-top:auto;">
            <button style="padding:8px;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="GoBack">
                Quay lại
            </button>
            <button class="pos-btn-checkout" @onclick="Complete"
                    disabled="@(_remainingBalance > 0)">
                Hoàn tất thanh toán
            </button>
        </div>
    </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;

    private bool _isLoading = true;
    private string? _errorMessage;

    // EN: Order total loaded from Order Service API.
    // VI: Tổng đơn hàng được tải từ Order Service API.
    private decimal _orderTotal = 0;

    private readonly List<PaymentSplit> _splits = new();

    private readonly List<AddOption> _addOptions = new()
    {
        new("💵", "Tiền mặt"),
        new("💳", "Thẻ"),
        new("📱", "Mã QR"),
        new("🎁", "Thẻ quà tặng"),
    };

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

    /// <summary>
    /// EN: Load order total from Order Service API (FRONT-W-03).
    /// VI: Tải tổng đơn hàng từ Order Service API (FRONT-W-03).
    /// </summary>
    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 decimal _paidAmount => _splits.Sum(s => s.Amount);
    private decimal _remainingBalance => Math.Max(0, _orderTotal - _paidAmount);
    private int _progressPercent => (int)Math.Min(100, _paidAmount / _orderTotal * 100);

    private void AddSplit(AddOption option)
    {
        _splits.Add(new(option.Icon, option.Label, "Mới thêm", _remainingBalance));
    }

    private void RemoveSplit(PaymentSplit split) => _splits.Remove(split);
    private void Complete() => NavigateTo($"payment/success?orderId={_resolvedOrderId}");
    private void GoBack() => NavigateTo($"payment/method-select?orderId={_resolvedOrderId}");

    private record AddOption(string Icon, string Label);
    private class PaymentSplit(string icon, string method, string description, decimal amount)
    {
        public string Icon { get; set; } = icon;
        public string Method { get; set; } = method;
        public string Description { get; set; } = description;
        public decimal Amount { get; set; } = amount;
    }
}
