@*
    EN: Karaoke F&B Order — Food & beverage ordering for active room session. Creates real orders via API.
    VI: Gọi F&B Karaoke — Đặt đồ ăn thức uống cho phiên phòng. Tạo đơn hàng thật qua API.
*@
@page "/pos/{ShopId:guid}/karaoke/order-fnb/{RoomId:guid}"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

@* ═══ PRODUCT PANEL (LEFT) / PANEL SẢN PHẨM (TRÁI) ═══ *@
<div class="pos-product-panel">
    @* EN: Header + room info / VI: Tiêu đề + thông tin phòng *@
    <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);">
        <button style="background:var(--pos-bg-interactive);border:none;color:var(--pos-text-primary);
                       padding:8px 12px;border-radius:8px;cursor:pointer;font-size:13px;"
                @onclick="@(() => NavigateTo($"karaoke/room-session/{RoomId}"))">
            <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
        </button>
        <span style="font-size:16px;font-weight:700;">Gọi F&B</span>
        <span style="font-size:12px;color:var(--pos-text-tertiary);margin-left:auto;">@_roomName</span>
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu
        </div>
    }
    else
    {
    @* EN: Category tabs / VI: 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>

    @* ═══ PRODUCT GRID / LƯỚI SẢN PHẨM ═══ *@
    <div class="pos-product-grid">
        @foreach (var product in FilteredProducts)
        {
            <div class="pos-product-card" @onclick="() => AddToOrder(product)">
                <div class="pos-product-card__image" style="display:flex;align-items:center;justify-content:center;">
                    <i data-lucide="@GetCategoryIcon(product.Category)"
                       style="width:28px;height:28px;color:var(--pos-text-tertiary);"></i>
                </div>
                <span class="pos-product-card__name">@product.Name</span>
                <span class="pos-product-card__price">@FormatPrice(product.Price)</span>
            </div>
        }
    </div>
    }
</div>

@* ═══ ORDER PANEL (RIGHT) / PANEL ĐƠN HÀNG (PHẢI) ═══ *@
<div class="pos-cart-panel">
    <div class="pos-cart-header">
        <span class="pos-cart-header__title">Đơn F&B</span>
        <span style="font-size:12px;color:var(--pos-text-tertiary);">@_orderItems.Count món</span>
    </div>

    <div class="pos-cart-items">
        @if (_orderItems.Any())
        {
            @foreach (var item in _orderItems)
            {
                <div class="pos-cart-item">
                    <div class="pos-cart-item__info">
                        <span class="pos-cart-item__name">@item.Name</span>
                        <span class="pos-cart-item__price">@FormatPrice(item.Price)</span>
                    </div>
                    <div class="pos-cart-item__qty">
                        <button @onclick="() => ChangeQty(item, -1)">−</button>
                        <span style="font-size:14px;font-weight:600;min-width:20px;text-align:center;">@item.Qty</span>
                        <button @onclick="() => ChangeQty(item, 1)">+</button>
                    </div>
                </div>
            }
        }
        else
        {
            <div style="text-align:center;padding:32px 16px;color:var(--pos-text-tertiary);font-size:13px;">
                Chọn món để thêm vào đơn
            </div>
        }
    </div>

    <div class="pos-cart-footer">
        @if (!string.IsNullOrEmpty(_statusMsg))
        {
            <div style="font-size:12px;margin-bottom:8px;color:@(_orderSuccess ? "#22C55E" : "#EF4444");">@_statusMsg</div>
        }
        <div class="pos-cart-total">
            <span class="pos-cart-total__label">Tổng F&B</span>
            <span class="pos-cart-total__value">@FormatPrice(_orderItems.Sum(i => i.Price * i.Qty))</span>
        </div>
        <button class="pos-btn-checkout" disabled="@(_submitting || !_orderItems.Any())" @onclick="SubmitOrder">
            @if (_submitting)
            {
                <text>Đang gửi...</text>
            }
            else
            {
                <i data-lucide="send" style="width:18px;height:18px;"></i> <text> Gửi đơn</text>
            }
        </button>
    </div>
</div>

@code {
    [Parameter] public Guid RoomId { get; set; }

    private bool _isLoading = true;
    private bool _loadError;
    private bool _submitting;
    private bool _orderSuccess;
    private string? _statusMsg;
    private string _roomName = "";

    private string _activeCategory = "Tất cả";
    private string[] _categories = { "Tất cả" };
    private List<Product> _products = new();
    private readonly List<OrderItem> _orderItems = new();

    private IEnumerable<Product> FilteredProducts =>
        _activeCategory == "Tất cả" ? _products : _products.Where(p => p.Category == _activeCategory);

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

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

            // Get room name
            var tables = await tablesTask;
            var room = tables.FirstOrDefault(t => t.Id == RoomId);
            _roomName = room?.TableNumber ?? "Phòng";

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

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

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

    private void AddToOrder(Product p)
    {
        var existing = _orderItems.FirstOrDefault(i => i.ProductId == p.Id);
        if (existing != null) existing.Qty++;
        else _orderItems.Add(new OrderItem(p.Id, p.Name, p.Price));
    }

    private void ChangeQty(OrderItem item, int delta)
    {
        item.Qty += delta;
        if (item.Qty <= 0) _orderItems.Remove(item);
    }

    private async Task SubmitOrder()
    {
        if (!_orderItems.Any()) return;
        _submitting = true;
        _statusMsg = null;

        try
        {
            var items = _orderItems.Select(i => new WebClientTpos.Client.Services.PosDataService.PosOrderItemRequest(
                i.ProductId, i.Name, i.Qty, i.Price, "PreparedFood")).ToList();
            var req = new WebClientTpos.Client.Services.PosDataService.CreatePosOrderRequest(
                ShopId, null, items, null, null, null, RoomId);
            var result = await DataService.CreatePosOrderAsync(req);
            if (result != null)
            {
                _orderSuccess = true;
                _statusMsg = "Đơn F&B đã gửi thành công!";
                _orderItems.Clear();
            }
            else
            {
                _orderSuccess = false;
                _statusMsg = "Không thể gửi đơn. Vui lòng thử lại.";
            }
        }
        catch
        {
            _orderSuccess = false;
            _statusMsg = "Lỗi khi gửi đơn.";
        }
        finally
        {
            _submitting = false;
        }
    }

    private static string GetCategoryIcon(string cat) => cat switch
    {
        "Đồ uống" => "wine", "Đồ ăn" => "utensils", "Mồi" => "popcorn", _ => "package"
    };

    private record Product(Guid Id, string Name, decimal Price, string Category);
    private class OrderItem(Guid productId, string name, decimal price)
    {
        public Guid ProductId { get; set; } = productId;
        public string Name { get; set; } = name;
        public decimal Price { get; set; } = price;
        public int Qty { get; set; } = 1;
    }
}
