@*
    EN: Restaurant Menu Management — Category tabs, item grid, edit mode, quick actions, stats.
    VI: Quản lý thực đơn nhà hàng — Tab danh mục, lưới món, chế độ chỉnh sửa, thao tác nhanh, thống kê.
*@
@page "/pos/{ShopId:guid}/restaurant/menu-management"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER / TIÊU ĐỀ ═══ *@
    <div style="padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);display:flex;align-items:center;gap:12px;">
        <button class="pos-category-tab" @onclick="@(() => NavigateTo("restaurant"))">
            <i data-lucide="arrow-left" style="width:14px;"></i> Quay lại
        </button>
        <span style="font-size:16px;font-weight:700;">
            <i data-lucide="book-open" style="width:18px;height:18px;display:inline;"></i> Quản lý thực đơn
        </span>
        <span style="flex:1;"></span>
        <button class="pos-category-tab pos-category-tab--active" @onclick="() => _editMode = !_editMode">
            <i data-lucide="@(_editMode ? "eye" : "pencil")" style="width:14px;"></i>
            @(_editMode ? "Xem" : "Chỉnh sửa")
        </button>
    </div>

    @* ═══ CATEGORY TABS / TAB DANH MỤC ═══ *@
    <div class="pos-category-tabs">
        @foreach (var cat in _categories)
        {
            <button class="pos-category-tab @(cat == _activeCategory ? "pos-category-tab--active" : "")"
                    @onclick="() => _activeCategory = cat">@cat</button>
        }
    </div>

    @* ═══ QUICK ACTIONS / THAO TÁC NHANH ═══ *@
    @if (_editMode)
    {
        <div style="padding:8px 16px;display:flex;gap:8px;border-bottom:1px solid var(--pos-border-subtle);">
            <button style="padding:8px 14px;border-radius:8px;border:1px solid var(--pos-danger);
                           background:rgba(239,68,68,.1);color:var(--pos-danger);font-size:12px;font-weight:600;cursor:pointer;"
                    @onclick="MarkSoldOut">
                <i data-lucide="x-circle" style="width:12px;height:12px;display:inline;"></i> Hết món (86)
            </button>
            <button style="padding:8px 14px;border-radius:8px;border:1px solid var(--pos-orange-primary);
                           background:rgba(255,92,0,.1);color:var(--pos-orange-primary);font-size:12px;font-weight:600;cursor:pointer;">
                <i data-lucide="star" style="width:12px;height:12px;display:inline;"></i> Đặc biệt hôm nay
            </button>
            <button style="padding:8px 14px;border-radius:8px;border:1px solid var(--pos-success);
                           background:rgba(34,197,94,.1);color:var(--pos-success);font-size:12px;font-weight:600;cursor:pointer;">
                <i data-lucide="percent" style="width:12px;height:12px;display:inline;"></i> Giảm giá
            </button>
        </div>
    }

    @* ═══ MENU ITEM GRID / LƯỚI MÓN ═══ *@
    <div style="flex:1;overflow-y:auto;padding: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
        {
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;">
            @foreach (var item in FilteredMenu)
            {
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);overflow:hidden;
                            opacity:@(item.Available ? "1" : "0.5");
                            border:2px solid @(_selectedItem == item.Name ? "var(--pos-orange-primary)" : "transparent");"
                     @onclick="() => _selectedItem = item.Name">
                    @* EN: Photo placeholder / VI: Ảnh giữ chỗ *@
                    <div style="height:100px;background:var(--pos-bg-interactive);display:flex;align-items:center;justify-content:center;position:relative;">
                        <i data-lucide="@item.Icon" style="width:32px;height:32px;color:var(--pos-text-tertiary);"></i>
                        @if (!item.Available)
                        {
                            <div style="position:absolute;top:8px;right:8px;background:var(--pos-danger);color:#fff;
                                        font-size:10px;font-weight:700;padding:2px 8px;border-radius:4px;">86</div>
                        }
                    </div>
                    <div style="padding:12px;">
                        <div style="font-size:13px;font-weight:600;margin-bottom:4px;">@item.Name</div>
                        <div style="display:flex;justify-content:space-between;align-items:center;">
                            <span style="font-size:14px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(item.Price)</span>
                            @if (_editMode)
                            {
                                <button style="width:28px;height:28px;border-radius:50%;border:none;cursor:pointer;
                                               background:@(item.Available ? "rgba(34,197,94,.15)" : "rgba(239,68,68,.15)");
                                               color:@(item.Available ? "var(--pos-success)" : "var(--pos-danger)");font-size:14px;"
                                        @onclick="() => item.Available = !item.Available"
                                        @onclick:stopPropagation="true">
                                    @(item.Available ? "✓" : "✗")
                                </button>
                            }
                        </div>
                        @if (!string.IsNullOrEmpty(item.Note))
                        {
                            <div style="font-size:11px;color:var(--pos-warning);margin-top:4px;font-style:italic;">@item.Note</div>
                        }
                    </div>
                </div>
            }
        </div>
        }
    </div>

    @* ═══ STATS BAR / THANH THỐNG KÊ ═══ *@
    <div style="padding:10px 16px;border-top:1px solid var(--pos-border-subtle);display:flex;gap:20px;font-size:12px;color:var(--pos-text-secondary);">
        <span>Tổng: <b>@_menuItems.Count</b> món</span>
        <span style="color:var(--pos-success);">Có sẵn: @_menuItems.Count(i => i.Available)</span>
        <span style="color:var(--pos-danger);">Hết (86): @_menuItems.Count(i => !i.Available)</span>
        <span style="margin-left:auto;font-weight:600;">@_activeCategory</span>
    </div>
</div>

@code {

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

    private string _activeCategory = "Tất cả";
    private bool _editMode = false;
    private string? _selectedItem;
    private string[] _categories = { "Tất cả" };

    // EN: Menu items from API / VI: Các món từ API
    private List<RestMenuItem> _menuItems = new();

    private IEnumerable<RestMenuItem> FilteredMenu =>
        _activeCategory == "Tất cả" ? _menuItems : _menuItems.Where(m => m.Category == _activeCategory);

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

        try
        {
            var products = await DataService.GetProductsAsync(ShopId);

            _menuItems = products.Select(p => new RestMenuItem(
                p.Name,
                p.Price,
                p.Category ?? "Khác",
                "utensils",
                true,
                ""
            )).ToList();

            var cats = _menuItems.Select(m => m.Category).Distinct().ToList();
            _categories = new[] { "Tất cả" }.Concat(cats).ToArray();
            _activeCategory = _categories.First();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void MarkSoldOut()
    {
        if (_selectedItem is not null)
        {
            var item = _menuItems.FirstOrDefault(m => m.Name == _selectedItem);
            if (item is not null) item.Available = false;
        }
    }

    private class RestMenuItem(string name, decimal price, string category, string icon, bool available, string note)
    {
        public string Name { get; set; } = name;
        public decimal Price { get; set; } = price;
        public string Category { get; set; } = category;
        public string Icon { get; set; } = icon;
        public bool Available { get; set; } = available;
        public string Note { get; set; } = note;
    }
}
