@*
    EN: Split Bill — Equal split, by-item split, custom split modes for shared bills.
    VI: Tách hóa đơn — Chia đều, chia theo món, chia tùy chỉnh cho hóa đơn chung.
*@
@page "/pos/{ShopId:guid}/dialog/split-bill"
@page "/pos/{ShopId:guid}/dialog/split-bill/{OrderId:guid}"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject IJSRuntime JS
@inject PosDataService DataService

@if (_isLoading)
{
    <div class="pos-dialog-overlay">
        <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
{
    <div class="pos-dialog-overlay">
        <div style="width:100%;max-width:720px;background:var(--pos-bg-elevated);border-radius:16px;
                    display:flex;flex-direction:column;max-height:92vh;overflow:hidden;">

            @* ═══ HEADER / TIÊU ĐỀ ═══ *@
            <div style="padding:20px 24px;border-bottom:1px solid var(--pos-border-subtle);display:flex;align-items:center;gap:12px;">
                <div style="width:40px;height:40px;border-radius:10px;background:rgba(59,130,246,.15);display:flex;align-items:center;justify-content:center;">
                    <i data-lucide="split" style="width:20px;height:20px;color:#3B82F6;"></i>
                </div>
                <div style="flex:1;">
                    <div style="font-size:18px;font-weight:700;">Tách hóa đơn</div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);">Tổng: @FormatPrice(_billTotal) · @_splitCount người</div>
                </div>
                <button style="background:none;border:none;color:var(--pos-text-tertiary);cursor:pointer;padding:8px;"
                        @onclick="@(async () => await JS.InvokeVoidAsync("history.back"))">
                    <i data-lucide="x" style="width:20px;height:20px;"></i>
                </button>
            </div>

            @* ═══ SPLIT MODE TABS / TAB CHẾ ĐỘ CHIA ═══ *@
            <div style="padding:12px 24px;border-bottom:1px solid var(--pos-border-subtle);display:flex;gap:8px;">
                @foreach (var mode in _modes)
                {
                    <button style="flex:1;padding:10px;border-radius:var(--pos-radius);border:2px solid @(_activeMode == mode.Key ? "var(--pos-orange-primary)" : "var(--pos-border-default)");
                                   background:@(_activeMode == mode.Key ? "rgba(255,92,0,.1)" : "transparent");color:var(--pos-text-primary);
                                   cursor:pointer;font-size:13px;font-weight:@(_activeMode == mode.Key ? "600" : "400");"
                            @onclick="() => _activeMode = mode.Key">
                        @mode.Label
                    </button>
                }
            </div>

            <div style="flex:1;overflow-y:auto;padding:24px;">
                @if (_activeMode == "equal")
                {
                    @* ═══ EQUAL SPLIT / CHIA ĐỀU ═══ *@
                    <div style="text-align:center;margin-bottom:24px;">
                        <div style="font-size:14px;font-weight:600;margin-bottom:16px;">Số người chia</div>
                        <div style="display:flex;gap:8px;justify-content:center;margin-bottom:20px;">
                            @for (var i = 2; i <= 8; i++)
                            {
                                var count = i;
                                <button style="width:44px;height:44px;border-radius:10px;border:2px solid @(_splitCount == count ? "var(--pos-orange-primary)" : "var(--pos-border-default)");
                                               background:@(_splitCount == count ? "rgba(255,92,0,.1)" : "var(--pos-bg-interactive)");
                                               color:var(--pos-text-primary);cursor:pointer;font-size:16px;font-weight:600;"
                                        @onclick="() => UpdateSplitCount(count)">
                                    @count
                                </button>
                            }
                        </div>
                        <div style="font-size:42px;font-weight:700;color:var(--pos-orange-primary);margin-bottom:8px;">
                            @FormatPrice(Math.Round(_billTotal / _splitCount))
                        </div>
                        <div style="font-size:14px;color:var(--pos-text-tertiary);">mỗi người</div>
                    </div>

                    @* EN: Per-person breakdown / VI: Chi tiết từng người *@
                    <div style="display:grid;grid-template-columns:repeat(3, 1fr);gap:10px;">
                        @for (var i = 1; i <= _splitCount; i++)
                        {
                            var personNum = i;
                            <div style="background:var(--pos-bg-interactive);border-radius:var(--pos-radius);padding:14px;text-align:center;cursor:pointer;"
                                 @onclick="() => PayForPerson(personNum)">
                                <div style="font-size:12px;color:var(--pos-text-tertiary);margin-bottom:6px;">Người @personNum</div>
                                <div style="font-size:16px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(Math.Round(_billTotal / _splitCount))</div>
                                <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:4px;">Nhấn để thanh toán</div>
                            </div>
                        }
                    </div>
                }
                else if (_activeMode == "byitem")
                {
                    @* ═══ BY-ITEM SPLIT / CHIA THEO MÓN ═══ *@
                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
                        @for (var p = 0; p < 3; p++)
                        {
                            var personIdx = p;
                            <div style="background:var(--pos-bg-interactive);border-radius:var(--pos-radius);padding:14px;">
                                <div style="font-size:14px;font-weight:600;margin-bottom:10px;text-align:center;
                                            padding-bottom:8px;border-bottom:1px solid var(--pos-border-subtle);">
                                    Người @(personIdx + 1)
                                </div>
                                @foreach (var item in _billItems.Where(i => i.AssignedTo == personIdx))
                                {
                                    <div style="display:flex;justify-content:space-between;padding:6px 0;font-size:12px;">
                                        <span>@item.Name</span>
                                        <span style="font-weight:600;">@FormatPrice(item.Price)</span>
                                    </div>
                                }
                                <div style="display:flex;justify-content:space-between;padding-top:8px;margin-top:8px;
                                            border-top:1px solid var(--pos-border-subtle);font-size:14px;font-weight:700;">
                                    <span>Tổng</span>
                                    <span style="color:var(--pos-orange-primary);">@FormatPrice(_billItems.Where(i => i.AssignedTo == personIdx).Sum(i => i.Price))</span>
                                </div>
                            </div>
                        }
                    </div>

                    @* EN: Unassigned items / VI: Món chưa gán *@
                    @if (UnassignedItems.Any())
                    {
                        <div style="margin-top:16px;padding:14px;background:rgba(245,158,11,.08);border-radius:var(--pos-radius);
                                    border:1px dashed var(--pos-warning);">
                            <div style="font-size:13px;font-weight:600;color:var(--pos-warning);margin-bottom:8px;">Chưa phân</div>
                            @foreach (var item in UnassignedItems)
                            {
                                <div style="display:flex;justify-content:space-between;align-items:center;padding:6px 0;font-size:12px;">
                                    <span>@item.Name — @FormatPrice(item.Price)</span>
                                    <div style="display:flex;gap:4px;">
                                        @for (var p = 0; p < 3; p++)
                                        {
                                            var targetPerson = p;
                                            <button style="width:28px;height:28px;border-radius:6px;border:1px solid var(--pos-border-default);
                                                           background:var(--pos-bg-elevated);color:var(--pos-text-primary);cursor:pointer;font-size:11px;"
                                                    @onclick="() => item.AssignedTo = targetPerson">
                                                @(targetPerson + 1)
                                            </button>
                                        }
                                    </div>
                                </div>
                            }
                        </div>
                    }
                }
                else
                {
                    @* ═══ CUSTOM SPLIT / CHIA TÙY CHỈNH ═══ *@
                    <div style="display:flex;flex-direction:column;gap:12px;">
                        @for (var i = 0; i < _splitCount; i++)
                        {
                            var idx = i;
                            <div style="display:flex;align-items:center;gap:12px;background:var(--pos-bg-interactive);
                                        border-radius:var(--pos-radius);padding:14px;">
                                <div style="width:36px;height:36px;border-radius:8px;background:var(--pos-bg-elevated);
                                            display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;">
                                    @(idx + 1)
                                </div>
                                <div style="flex:1;">
                                    <div style="font-size:13px;font-weight:600;margin-bottom:4px;">Người @(idx + 1)</div>
                                    <input type="number" @bind="_customAmounts[idx]" placeholder="Nhập số tiền..."
                                           style="width:100%;padding:8px 12px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                                                  background:var(--pos-bg-elevated);color:var(--pos-text-primary);font-size:14px;font-weight:600;" />
                                </div>
                                <div style="font-size:14px;font-weight:700;color:var(--pos-orange-primary);min-width:80px;text-align:right;">
                                    @FormatPrice(_customAmounts[idx])
                                </div>
                            </div>
                        }
                    </div>

                    @* EN: Remaining amount / VI: Số tiền còn lại *@
                    <div style="margin-top:16px;padding:14px;border-radius:var(--pos-radius);
                                background:@(CustomRemaining == 0 ? "rgba(34,197,94,.1)" : "rgba(245,158,11,.1)");
                                border:1px solid @(CustomRemaining == 0 ? "rgba(34,197,94,.3)" : "rgba(245,158,11,.3)");
                                display:flex;justify-content:space-between;align-items:center;">
                        <span style="font-size:13px;font-weight:600;color:@(CustomRemaining == 0 ? "var(--pos-success)" : "var(--pos-warning)");">
                            @(CustomRemaining == 0 ? "Đã chia hết!" : "Còn thiếu")
                        </span>
                        <span style="font-size:16px;font-weight:700;color:@(CustomRemaining == 0 ? "var(--pos-success)" : "var(--pos-warning)");">
                            @FormatPrice(Math.Abs(CustomRemaining))
                        </span>
                    </div>
                }
            </div>

            @* ═══ FOOTER / CUỐI TRANG ═══ *@
            <div style="padding:16px 24px;border-top:1px solid var(--pos-border-subtle);display:flex;gap:10px;">
                <button style="flex:1;padding:14px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                               background:transparent;color:var(--pos-text-primary);cursor:pointer;font-size:14px;"
                        @onclick="@(async () => await JS.InvokeVoidAsync("history.back"))">
                    Hủy
                </button>
                <button style="flex:2;padding:14px;border-radius:var(--pos-radius);border:none;
                               background:var(--pos-orange-primary);color:#fff;cursor:pointer;font-size:14px;font-weight:600;"
                        @onclick="GenerateSplitBills">
                    <i data-lucide="receipt" style="width:16px;height:16px;vertical-align:middle;margin-right:4px;"></i>
                    Tạo hóa đơn riêng
                </button>
            </div>
        </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 bool _isLoading = true;

    // EN: Split state / VI: Trạng thái tách
    private string _activeMode = "equal";
    private int _splitCount = 2;
    private decimal _billTotal;

    // EN: Split mode definitions / VI: Định nghĩa chế độ chia
    private readonly List<SplitMode> _modes = new()
    {
        new("equal", "Chia đều"),
        new("byitem", "Chia theo món"),
        new("custom", "Chia tùy chỉnh"),
    };

    // EN: Bill items for by-item split / VI: Danh sách món để chia theo món
    private List<SplitItem> _billItems = new();

    // EN: Custom amounts / VI: Số tiền tùy chỉnh
    private decimal[] _customAmounts = new decimal[8];

    // EN: Computed properties for template / VI: Thuộc tính tính toán cho template
    private List<SplitItem> UnassignedItems => _billItems.Where(i => i.AssignedTo < 0).ToList();
    private decimal CustomRemaining => _billTotal - _customAmounts.Take(_splitCount).Sum();

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

    private async Task LoadOrderAsync()
    {
        _isLoading = true;
        try
        {
            if (_resolvedOrderId == Guid.Empty) { _isLoading = false; return; }
            var detail = await DataService.GetOrderDetailAsync(_resolvedOrderId, ShopId);
            if (detail?.Order != null)
            {
                _billTotal = detail.Order.TotalAmount;
            }
            if (detail?.Items != null)
            {
                _billItems = detail.Items.Select(i => new SplitItem(
                    i.ProductName ?? "Sản phẩm",
                    i.Subtotal,
                    -1 // EN: Unassigned by default / VI: Chưa phân mặc định
                )).ToList();
            }
            // EN: Initialize custom amounts with equal split default.
            // VI: Khởi tạo số tiền tùy chỉnh với chia đều mặc định.
            UpdateCustomAmountsDefault();
        }
        catch { /* graceful */ }
        finally { _isLoading = false; }
    }

    private void UpdateSplitCount(int count)
    {
        _splitCount = count;
        UpdateCustomAmountsDefault();
    }

    private void UpdateCustomAmountsDefault()
    {
        var perPerson = Math.Round(_billTotal / _splitCount);
        for (var i = 0; i < _customAmounts.Length; i++)
            _customAmounts[i] = i < _splitCount ? perPerson : 0;
        // EN: Adjust last person to account for rounding.
        // VI: Điều chỉnh người cuối để bù làm tròn.
        if (_splitCount > 0)
            _customAmounts[_splitCount - 1] = _billTotal - perPerson * (_splitCount - 1);
    }

    private void PayForPerson(int personNum)
    {
        // EN: Navigate to payment method select for this split portion.
        // VI: Điều hướng đến chọn phương thức thanh toán cho phần chia này.
        NavigationManager.NavigateTo($"/pos/{ShopId}/payment/method-select?orderId={_resolvedOrderId}");
    }

    private void GenerateSplitBills()
    {
        // EN: Navigate first person to payment method select.
        // VI: Điều hướng người đầu tiên đến chọn phương thức thanh toán.
        NavigationManager.NavigateTo($"/pos/{ShopId}/payment/method-select?orderId={_resolvedOrderId}");
    }

    private record SplitMode(string Key, string Label);

    private class SplitItem(string name, decimal price, int assignedTo)
    {
        public string Name { get; set; } = name;
        public decimal Price { get; set; } = price;
        public int AssignedTo { get; set; } = assignedTo;
    }
}
