@*
    EN: Edit Existing Order — Editable item list, quantity controls, add items, discount, notes, recalculated total.
    VI: Chỉnh sửa đơn hàng — Danh sách món chỉnh sửa, điều khiển số lượng, thêm món, giảm giá, ghi chú, tổng tính lại.
*@
@page "/pos/{ShopId:guid}/dialog/order-edit"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject IJSRuntime JS

<div class="pos-dialog-overlay">
    <div style="width:100%;max-width:640px;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="pencil" style="width:20px;height:20px;color:#3B82F6;"></i>
            </div>
            <div style="flex:1;">
                <div style="font-size:18px;font-weight:700;">Chỉnh sửa đơn hàng</div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);">Bàn 5 · 15:20 · Đang phục vụ</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>

        <div style="flex:1;overflow-y:auto;padding:24px;">
            @* ═══ ORDER INFO / THÔNG TIN ĐƠN HÀNG ═══ *@
            <div style="display:flex;gap:16px;margin-bottom:20px;">
                <div style="flex:1;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);padding:12px;">
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">Khách hàng</div>
                    <div style="font-size:14px;font-weight:600;">Bàn 5 — 4 khách</div>
                </div>
                <div style="flex:1;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);padding:12px;">
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">Nhân viên</div>
                    <div style="font-size:14px;font-weight:600;">Trần Thị B</div>
                </div>
                <div style="flex:1;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);padding:12px;">
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">Trạng thái</div>
                    <div style="font-size:14px;font-weight:600;color:var(--pos-success);">Đang phục vụ</div>
                </div>
            </div>

            @* ═══ EDITABLE ITEM LIST / DANH SÁCH MÓN CHỈNH SỬA ═══ *@
            <div style="font-size:14px;font-weight:600;margin-bottom:12px;">Danh sách món</div>
            <div style="display:flex;flex-direction:column;gap:8px;margin-bottom:20px;">
                @foreach (var item in _items)
                {
                    <div style="display:flex;align-items:center;gap:12px;padding:12px;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);">
                        <div style="flex:1;">
                            <div style="font-size:14px;font-weight:500;">@item.Name</div>
                            <div style="font-size:12px;color:var(--pos-text-tertiary);">@FormatPrice(item.Price)</div>
                        </div>
                        <div style="display:flex;align-items:center;gap:6px;">
                            <button style="width:30px;height:30px;border-radius:6px;border:1px solid var(--pos-border-default);
                                           background:var(--pos-bg-elevated);color:var(--pos-text-primary);cursor:pointer;font-size:16px;"
                                    @onclick="() => item.Qty = Math.Max(0, item.Qty - 1)">−</button>
                            <span style="min-width:28px;text-align:center;font-size:15px;font-weight:600;">@item.Qty</span>
                            <button style="width:30px;height:30px;border-radius:6px;border:1px solid var(--pos-border-default);
                                           background:var(--pos-bg-elevated);color:var(--pos-text-primary);cursor:pointer;font-size:16px;"
                                    @onclick="() => item.Qty++">+</button>
                        </div>
                        <span style="min-width:80px;text-align:right;font-size:14px;font-weight:600;">@FormatPrice(item.Price * item.Qty)</span>
                        <button style="background:none;border:none;color:var(--pos-danger);cursor:pointer;padding:4px;"
                                @onclick="() => _items.Remove(item)">
                            <i data-lucide="trash-2" style="width:16px;height:16px;"></i>
                        </button>
                    </div>
                }
            </div>

            @* ═══ ADD ITEM / THÊM MÓN ═══ *@
            <div style="margin-bottom:20px;">
                <div style="font-size:14px;font-weight:600;margin-bottom:10px;">Thêm món</div>
                <div style="display:flex;gap:8px;margin-bottom:10px;">
                    <input type="text" @bind="_searchTerm" placeholder="Tìm kiếm món..."
                           style="flex:1;padding:10px 14px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                                  background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:13px;" />
                </div>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    @foreach (var quick in _quickAddItems)
                    {
                        <button style="padding:8px 14px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                                       background:var(--pos-bg-interactive);color:var(--pos-text-primary);cursor:pointer;font-size:12px;"
                                @onclick="() => AddItem(quick)">
                            <i data-lucide="plus" style="width:12px;height:12px;vertical-align:middle;margin-right:4px;"></i>
                            @quick.Name — @FormatPrice(quick.Price)
                        </button>
                    }
                </div>
            </div>

            @* ═══ DISCOUNT / GIẢM GIÁ ═══ *@
            <div style="margin-bottom:20px;">
                <div style="font-size:14px;font-weight:600;margin-bottom:10px;">Giảm giá</div>
                <div style="display:flex;gap:10px;align-items:center;">
                    <div style="display:flex;gap:6px;">
                        <button style="padding:8px 16px;border-radius:var(--pos-radius);border:2px solid @(_discountType == "percent" ? "var(--pos-orange-primary)" : "var(--pos-border-default)");
                                       background:@(_discountType == "percent" ? "rgba(255,92,0,.1)" : "var(--pos-bg-interactive)");color:var(--pos-text-primary);cursor:pointer;font-size:13px;"
                                @onclick='() => _discountType = "percent"'>%</button>
                        <button style="padding:8px 16px;border-radius:var(--pos-radius);border:2px solid @(_discountType == "fixed" ? "var(--pos-orange-primary)" : "var(--pos-border-default)");
                                       background:@(_discountType == "fixed" ? "rgba(255,92,0,.1)" : "var(--pos-bg-interactive)");color:var(--pos-text-primary);cursor:pointer;font-size:13px;"
                                @onclick='() => _discountType = "fixed"'>₫</button>
                    </div>
                    <input type="number" @bind="_discountValue" placeholder="0"
                           style="width:120px;padding:10px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                                  background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:14px;" />
                </div>
            </div>

            @* ═══ SPECIAL NOTE / GHI CHÚ ĐẶC BIỆT ═══ *@
            <div style="margin-bottom:16px;">
                <div style="font-size:14px;font-weight:600;margin-bottom:10px;">Ghi chú đặc biệt</div>
                <textarea @bind="_specialNote" rows="2" placeholder="VD: Không hành, thêm ớt..."
                          style="width:100%;padding:10px 14px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);
                                 background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:13px;resize:vertical;box-sizing:border-box;"></textarea>
            </div>
        </div>

        @* ═══ FOOTER — TOTAL & SAVE / CUỐI — TỔNG & LƯU ═══ *@
        <div style="padding:16px 24px;border-top:1px solid var(--pos-border-subtle);">
            <div style="display:flex;justify-content:space-between;font-size:13px;color:var(--pos-text-secondary);margin-bottom:6px;">
                <span>Tạm tính</span><span>@FormatPrice(Subtotal)</span>
            </div>
            @if (DiscountAmount > 0)
            {
                <div style="display:flex;justify-content:space-between;font-size:13px;color:var(--pos-danger);margin-bottom:6px;">
                    <span>Giảm giá</span><span>-@FormatPrice(DiscountAmount)</span>
                </div>
            }
            <div style="display:flex;justify-content:space-between;font-size:18px;font-weight:700;margin-bottom:14px;">
                <span>Tổng cộng</span>
                <span style="color:var(--pos-orange-primary);">@FormatPrice(Total)</span>
            </div>
            <div style="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="SaveChanges">
                    <i data-lucide="save" style="width:16px;height:16px;vertical-align:middle;margin-right:4px;"></i>
                    Lưu thay đổi
                </button>
            </div>
        </div>
    </div>
</div>

@code {
    // EN: Dialog data — populated from current context (selected order/product).
    // VI: Dữ liệu dialog — được điền từ context hiện tại (đơn hàng/sản phẩm đã chọn).
    // TODO: Integrate with Order/Catalog/Inventory APIs when DDD Value Object mapping is fixed.

    // EN: Edit state / VI: Trạng thái chỉnh sửa
    private string _searchTerm = "";
    private string _discountType = "percent";
    private decimal _discountValue = 10;
    private string _specialNote = "Không hành cho món Phở";

    // EN: Demo order items for "Bàn 5" / VI: Danh sách món mẫu "Bàn 5"
    private readonly List<EditableItem> _items = new()
    {
        new("Phở bò tái", 75_000, 2),
        new("Cơm tấm sườn bì chả", 65_000, 1),
        new("Gỏi cuốn tôm thịt", 45_000, 1),
        new("Trà đá", 10_000, 4),
    };

    // EN: Quick-add suggestions / VI: Gợi ý thêm nhanh
    private readonly List<QuickItem> _quickAddItems = new()
    {
        new("Chả giò", 40_000),
        new("Bánh flan", 25_000),
        new("Nước suối", 15_000),
        new("Bia Sài Gòn", 25_000),
    };

    private decimal Subtotal => _items.Where(i => i.Qty > 0).Sum(i => i.Price * i.Qty);

    private decimal DiscountAmount => _discountType == "percent"
        ? Math.Round(Subtotal * _discountValue / 100)
        : Math.Min(_discountValue, Subtotal);

    private decimal Total => Math.Max(0, Subtotal - DiscountAmount);

    private void AddItem(QuickItem quick)
    {
        var existing = _items.FirstOrDefault(i => i.Name == quick.Name);
        if (existing != null)
            existing.Qty++;
        else
            _items.Add(new EditableItem(quick.Name, quick.Price, 1));
    }

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

    private class EditableItem(string name, decimal price, int qty)
    {
        public string Name { get; set; } = name;
        public decimal Price { get; set; } = price;
        public int Qty { get; set; } = qty;
    }

    private record QuickItem(string Name, decimal Price);
}
