@*
    EN: Waiter Pad — Order taking by course with special requests, send to kitchen.
        Connected to POS order API for order creation with table association.
    VI: Pad Phuc vu — Goi mon theo course voi yeu cau dac biet, gui bep.
        Ket noi API POS order de tao don voi lien ket ban.
*@
@page "/pos/{ShopId:guid}/restaurant/waiter-pad/{TableId:guid}"
@page "/pos/{ShopId:guid}/restaurant/waiter-pad"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService

<div class="pos-product-panel" style="display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER / TIEU DE ═══ *@
    <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 lai
        </button>
        <span style="font-size:16px;font-weight:700;">Goi mon@(_tableName != null ? $" — {_tableName}" : "")</span>
        <span style="font-size:12px;color:var(--pos-text-tertiary);">PV: @(string.IsNullOrEmpty(StaffName) ? "Nhan vien" : StaffName)</span>
    </div>

    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Dang tai...
        </div>
    }
    else if (_loadError)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Khong the tai du lieu
        </div>
    }
    else
    {
        @* ═══ COURSE TABS / TAB MON THEO COURSE ═══ *@
        <div class="pos-category-tabs">
            @foreach (var c in _courses)
            {
                <button class="pos-category-tab @(c == _activeCourse ? "pos-category-tab--active" : "")"
                        @onclick="() => _activeCourse = c">@c</button>
            }
        </div>

        @* ═══ MENU ITEMS / DANH SACH MON ═══ *@
        <div class="pos-product-grid" style="grid-template-columns:repeat(auto-fill,minmax(150px,1fr));">
            @foreach (var item in FilteredMenu)
            {
                <div class="pos-product-card" @onclick="() => AddToOrder(item)">
                    <div class="pos-product-card__image" style="display:flex;align-items:center;justify-content:center;">
                        <i data-lucide="@item.Icon" style="width:28px;color:var(--pos-text-tertiary);"></i>
                    </div>
                    <span class="pos-product-card__name">@item.Name</span>
                    <span class="pos-product-card__price">@FormatPrice(item.Price)</span>
                </div>
            }
        </div>
    }
</div>

@* ═══ ORDER PANEL / PANEL DON GOI ═══ *@
<div class="pos-cart-panel">
    <div class="pos-cart-header">
        <span class="pos-cart-header__title">Don goi (@_orderItems.Count mon)</span>
        <button style="background:none;border:none;color:var(--pos-danger);font-size:12px;cursor:pointer;"
                @onclick="ClearOrder">Xoa het</button>
    </div>

    <div class="pos-cart-items">
        @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>
                    @if (!string.IsNullOrEmpty(item.Note))
                    {
                        <span style="font-size:11px;color:var(--pos-warning);font-style:italic;">&#128221; @item.Note</span>
                    }
                </div>
                <div class="pos-cart-item__qty">
                    <button @onclick="() => ChangeQty(item, -1)">-</button>
                    <span style="font-size:13px;font-weight:600;">@item.Qty</span>
                    <button @onclick="() => ChangeQty(item, 1)">+</button>
                </div>
            </div>
        }
    </div>

    @* ═══ SPECIAL REQUEST / YEU CAU DAC BIET ═══ *@
    <div style="padding:8px 16px;">
        <input type="text" @bind="_specialRequest" placeholder="Ghi chu dac biet..."
               style="width:100%;padding:10px 12px;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;font-family:var(--pos-font);" />
    </div>

    @if (!string.IsNullOrEmpty(_submitMessage))
    {
        <div style="padding:0 16px 8px;font-size:12px;color:@(_submitIsError ? "var(--pos-danger)" : "var(--pos-success)");">@_submitMessage</div>
    }

    <div class="pos-cart-footer">
        <div class="pos-cart-total">
            <span class="pos-cart-total__label">Tong</span>
            <span class="pos-cart-total__value">@FormatPrice(_orderItems.Sum(i => i.Price * i.Qty))</span>
        </div>
        <button class="pos-btn-checkout" disabled="@(_isSending || !_orderItems.Any())" @onclick="SendToKitchen">
            @if (_isSending)
            {
                <span>Dang gui...</span>
            }
            else
            {
                <i data-lucide="send"></i>
                <span>Gui bep</span>
            }
        </button>
    </div>
</div>

@code {

    // EN: Route parameter for table association / VI: Tham so route de lien ket ban
    [Parameter] public Guid TableId { get; set; }

    // EN: Loading state / VI: Trang thai tai
    private bool _isLoading = true;
    private bool _loadError;

    // EN: Submit state / VI: Trang thai gui
    private bool _isSending;
    private string? _submitMessage;
    private bool _submitIsError;

    private string _activeCourse = "Tat ca";
    private string _specialRequest = string.Empty;
    private string[] _courses = { "Tat ca" };
    private string? _tableName;

    // EN: Menu items from API / VI: Thuc don tu API
    private List<MenuItem> _menu = new();

    private IEnumerable<MenuItem> FilteredMenu =>
        _activeCourse == "Tat ca" ? _menu : _menu.Where(m => m.Course == _activeCourse);

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

        try
        {
            // EN: Load products and categories in parallel / VI: Tai san pham va danh muc song song
            var productsTask = DataService.GetProductsAsync(ShopId);
            var categoriesTask = DataService.GetCategoriesAsync(ShopId);

            // EN: Load table info if TableId provided / VI: Tai thong tin ban neu co TableId
            Task<List<PosDataService.TableInfo>>? tablesTask = null;
            if (TableId != Guid.Empty)
            {
                tablesTask = DataService.GetTablesAsync(ShopId);
            }

            await Task.WhenAll(productsTask, categoriesTask);
            if (tablesTask != null) await tablesTask;

            var products = await productsTask;
            var categories = await categoriesTask;
            var categoryMap = categories.ToDictionary(c => c.Id, c => c.Name);

            _menu = products.Select(p => new MenuItem(
                p.Id,
                p.Name,
                p.Price,
                p.Category ?? categoryMap.GetValueOrDefault(Guid.Empty, "Khac"),
                "utensils"
            )).ToList();

            var courseNames = _menu.Select(m => m.Course).Distinct().ToList();
            _courses = new[] { "Tat ca" }.Concat(courseNames).ToArray();
            _activeCourse = _courses.First();

            // EN: Set table name if found / VI: Dat ten ban neu tim thay
            if (tablesTask != null)
            {
                var tables = await tablesTask;
                var table = tables.FirstOrDefault(t => t.Id == TableId);
                if (table != null)
                {
                    _tableName = $"Ban {table.TableNumber}";
                }
            }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    // EN: Current order / VI: Don goi hien tai
    private readonly List<OrderLine> _orderItems = new();

    private void AddToOrder(MenuItem item)
    {
        var existing = _orderItems.FirstOrDefault(o => o.ProductId == item.ProductId);
        if (existing is not null) existing.Qty++;
        else _orderItems.Add(new OrderLine(item.ProductId, item.Name, item.Price, 1, ""));
    }

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

    private void ClearOrder()
    {
        _orderItems.Clear();
        _submitMessage = null;
    }

    private async Task SendToKitchen()
    {
        if (!_orderItems.Any()) return;

        _isSending = true;
        _submitMessage = null;

        try
        {
            // EN: Build order items with product IDs / VI: Tao danh sach mon voi ID san pham
            var items = _orderItems.Select(o => new PosDataService.PosOrderItemRequest(
                o.ProductId,
                o.Name,
                o.Qty,
                o.Price,
                "Physical"
            )).ToList();

            var req = new PosDataService.CreatePosOrderRequest(
                ShopId,
                null, // EN: No payment method yet / VI: Chua co phuong thuc thanh toan
                items,
                TableId: TableId != Guid.Empty ? TableId : null
            );

            var result = await DataService.CreatePosOrderAsync(req);

            if (result != null)
            {
                // EN: Order created successfully — clear cart and navigate
                // VI: Tao don thanh cong — xoa gio va chuyen trang
                _orderItems.Clear();
                _specialRequest = string.Empty;
                NavigateTo("restaurant/kitchen-display");
            }
            else
            {
                _submitMessage = "Khong the tao don. Vui long thu lai.";
                _submitIsError = true;
            }
        }
        catch
        {
            _submitMessage = "Loi khi gui bep. Vui long thu lai.";
            _submitIsError = true;
        }
        finally
        {
            _isSending = false;
        }
    }

    private record MenuItem(Guid ProductId, string Name, decimal Price, string Course, string Icon);
    private class OrderLine(Guid productId, string name, decimal price, int qty, string note)
    {
        public Guid ProductId { get; set; } = productId;
        public string Name { get; set; } = name;
        public decimal Price { get; set; } = price;
        public int Qty { get; set; } = qty;
        public string Note { get; set; } = note;
    }
}
