@*
    EN: Menu Management — Quick menu: toggle availability, sold-out marking, price override.
    VI: Quản lý menu — Menu nhanh: bật/tắt khả dụng, đánh dấu hết hàng, ghi đè giá.
*@
@page "/pos/{ShopId:guid}/cafe/menu-management"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService

<div style="display:flex;flex-direction:column;height:100%;padding:20px;gap:16px;">
    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu
        </div>
    }
    else
    {
    @* EN: Header / VI: Tiêu đề *@
    <div style="display:flex;justify-content:space-between;align-items:center;">
        <div>
            <h2 style="font-size:20px;font-weight:700;margin:0;">Quản lý menu</h2>
            <span style="font-size:13px;color:var(--pos-text-tertiary);">Cập nhật tình trạng món — @_items.Count(i => i.Available) / @_items.Count có sẵn</span>
        </div>
        <div style="display:flex;gap:8px;align-items:center;">
            @foreach (var cat in _filterCategories)
            {
                <button class="pos-category-tab @(_filterCategory == cat ? "pos-category-tab--active" : "")"
                        @onclick="() => _filterCategory = cat">
                    @cat
                </button>
            }
            @* EN: Save Changes button / VI: Nút Lưu thay đổi *@
            <button style="padding:8px 16px;border-radius:var(--pos-radius);border:none;background:var(--pos-orange-primary);color:#fff;font-size:13px;font-weight:600;cursor:pointer;margin-left:8px;"
                    disabled="@(!HasChanges || _isSaving)"
                    @onclick="SaveChangesAsync">
                @if (_isSaving)
                {
                    <span>Đang lưu...</span>
                }
                else
                {
                    <i data-lucide="save" style="width:14px;height:14px;vertical-align:middle;margin-right:4px;"></i>
                    <span>Lưu thay đổi</span>
                }
            </button>
        </div>
    </div>
    @if (!string.IsNullOrEmpty(_saveMessage))
    {
        <div style="font-size:12px;padding:8px 12px;border-radius:8px;margin-top:8px;background:@(_saveIsError ? "rgba(239,68,68,0.1)" : "rgba(34,197,94,0.1)");color:@(_saveIsError ? "#EF4444" : "#16A34A");">
            @_saveMessage
        </div>
    }

    @* EN: Menu items table / VI: Bảng danh sách món *@
    <div style="flex:1;overflow-y:auto;">
        <div style="display:flex;flex-direction:column;gap:4px;">
            @* EN: Table header / VI: Header bảng *@
            <div style="display:grid;grid-template-columns:1fr 100px 120px 140px 80px;gap:12px;padding:10px 16px;font-size:12px;color:var(--pos-text-tertiary);font-weight:600;text-transform:uppercase;letter-spacing:0.5px;">
                <span>Tên món</span>
                <span>Danh mục</span>
                <span style="text-align:right;">Giá gốc</span>
                <span style="text-align:right;">Giá hiện tại</span>
                <span style="text-align:center;">Trạng thái</span>
            </div>

            @foreach (var item in FilteredItems)
            {
                <div style="display:grid;grid-template-columns:1fr 100px 120px 140px 80px;gap:12px;padding:14px 16px;background:var(--pos-bg-elevated);border-radius:var(--pos-radius);align-items:center;
                            opacity:@(item.Available ? "1" : "0.5");">
                    @* EN: Item name / VI: Tên món *@
                    <div style="display:flex;align-items:center;gap:12px;">
                        <div style="width:40px;height:40px;border-radius:8px;background:var(--pos-bg-interactive);display:flex;align-items:center;justify-content:center;">
                            <i data-lucide="coffee" style="width:18px;height:18px;color:var(--pos-text-tertiary);"></i>
                        </div>
                        <div>
                            <div style="font-size:14px;font-weight:500;">@item.Name</div>
                            @if (!item.Available)
                            {
                                <span style="font-size:10px;color:var(--pos-danger);font-weight:600;text-transform:uppercase;">Hết hàng</span>
                            }
                        </div>
                    </div>

                    @* EN: Category / VI: Danh mục *@
                    <span style="font-size:12px;color:var(--pos-text-tertiary);">@item.Category</span>

                    @* EN: Original price / VI: Giá gốc *@
                    <span style="font-size:13px;color:var(--pos-text-secondary);text-align:right;">@FormatPrice(item.OriginalPrice)</span>

                    @* EN: Current price (editable) / VI: Giá hiện tại (chỉnh sửa) *@
                    <div style="text-align:right;">
                        @if (item.IsEditingPrice)
                        {
                            <input type="number" value="@item.CurrentPrice" style="width:100px;padding:6px 8px;border-radius:6px;border:1px solid var(--pos-orange-primary);background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:13px;text-align:right;outline:none;"
                                   @onchange="@((ChangeEventArgs e) => { item.CurrentPrice = decimal.Parse(e.Value?.ToString() ?? "0"); item.IsEditingPrice = false; item.IsDirty = true; })" />
                        }
                        else
                        {
                            <span style="font-size:14px;font-weight:600;color:@(item.CurrentPrice != item.OriginalPrice ? "var(--pos-warning)" : "var(--pos-orange-primary)");cursor:pointer;"
                                  @onclick="() => item.IsEditingPrice = true">
                                @FormatPrice(item.CurrentPrice)
                                @if (item.CurrentPrice != item.OriginalPrice)
                                {
                                    <i data-lucide="pencil" style="width:10px;height:10px;vertical-align:middle;margin-left:4px;"></i>
                                }
                            </span>
                        }
                    </div>

                    @* EN: Toggle availability / VI: Bật/tắt khả dụng *@
                    <div style="text-align:center;">
                        <button style="width:44px;height:24px;border-radius:12px;border:none;cursor:pointer;position:relative;transition:background 0.2s;
                                       background:@(item.Available ? "var(--pos-success)" : "var(--pos-bg-interactive)");"
                                @onclick="() => ToggleAvailability(item)">
                            <span style="position:absolute;top:2px;width:20px;height:20px;border-radius:50%;background:#fff;transition:left 0.2s;
                                         left:@(item.Available ? "22px" : "2px");"></span>
                        </button>
                    </div>
                </div>
            }
        </div>
    </div>
    }
</div>

@code {

    // EN: Loading state / VI: Trạng thái tải
    private bool _isLoading = true;
    private bool _loadError;

    // EN: Save state / VI: Trạng thái lưu
    private bool _isSaving;
    private string? _saveMessage;
    private bool _saveIsError;

    private string _filterCategory = "Tất cả";
    private string[] _filterCategories = { "Tất cả" };

    private IEnumerable<MenuItem> FilteredItems =>
        _filterCategory == "Tất cả" ? _items : _items.Where(i => i.Category == _filterCategory);

    // EN: Check if any item has unsaved changes / VI: Kiểm tra có item nào chưa lưu không
    private bool HasChanges => _items.Any(i => i.IsDirty);

    // EN: Menu items loaded from DB / VI: Danh sách menu tải từ DB
    private List<MenuItem> _items = new();

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

        try
        {
            var productsTask = DataService.GetProductsAsync(ShopId);
            var categoriesTask = DataService.GetCategoriesAsync(ShopId);
            await Task.WhenAll(productsTask, categoriesTask);

            var apiProducts = await productsTask;
            var apiCategories = await categoriesTask;

            _items = apiProducts.Select(p => new MenuItem(
                p.Id,
                p.Name,
                p.Category ?? "Khác",
                p.Price,
                p.CategoryId
            )).ToList();

            var catNames = apiCategories.Select(c => c.Name).ToList();
            if (catNames.Count > 0)
                _filterCategories = new[] { "Tất cả" }.Concat(catNames).ToArray();
            else
            {
                var productCats = _items.Select(i => i.Category).Distinct().ToList();
                _filterCategories = new[] { "Tất cả" }.Concat(productCats).ToArray();
            }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    // EN: Toggle availability and mark item as dirty / VI: Bật/tắt khả dụng và đánh dấu item đã thay đổi
    private void ToggleAvailability(MenuItem item)
    {
        item.Available = !item.Available;
        item.IsDirty = true;
    }

    // EN: Save all changed items to API / VI: Lưu tất cả item đã thay đổi lên API
    private async Task SaveChangesAsync()
    {
        if (_isSaving || !HasChanges) return;
        _isSaving = true;
        _saveMessage = null;
        StateHasChanged();

        var dirtyItems = _items.Where(i => i.IsDirty).ToList();
        int successCount = 0;
        int failCount = 0;

        foreach (var item in dirtyItems)
        {
            try
            {
                // EN: Update product via admin API — send price and availability
                // VI: Cập nhật sản phẩm qua admin API — gửi giá và trạng thái khả dụng
                var req = new PosDataService.CreateProductRequest(
                    ShopId,
                    item.Name,
                    null, // description
                    item.CurrentPrice,
                    null, // type
                    null, // sku
                    null, // imageUrl
                    item.CategoryId
                );
                var success = await DataService.UpdateProductAsync(item.ProductId, req);
                if (success)
                {
                    item.OriginalPrice = item.CurrentPrice;
                    item.IsDirty = false;
                    successCount++;
                }
                else
                {
                    failCount++;
                }
            }
            catch
            {
                failCount++;
            }
        }

        if (failCount == 0)
        {
            _saveMessage = $"Đã lưu thành công {successCount} món.";
            _saveIsError = false;
        }
        else
        {
            _saveMessage = $"Lưu {successCount} thành công, {failCount} thất bại.";
            _saveIsError = true;
        }

        _isSaving = false;
        StateHasChanged();

        // EN: Auto-hide message after 3 seconds / VI: Tự động ẩn thông báo sau 3 giây
        await Task.Delay(3000);
        _saveMessage = null;
        StateHasChanged();
    }

    private class MenuItem(Guid productId, string name, string category, decimal price, Guid? categoryId = null)
    {
        public Guid ProductId { get; set; } = productId;
        public string Name { get; set; } = name;
        public string Category { get; set; } = category;
        public decimal OriginalPrice { get; set; } = price;
        public decimal CurrentPrice { get; set; } = price;
        public bool Available { get; set; } = true;
        public bool IsEditingPrice { get; set; }
        public bool IsDirty { get; set; }
        public Guid? CategoryId { get; set; } = categoryId;
    }
}
