@*
    EN: Restaurant POS Mobile — Single-column table list view, tap to order.
    VI: POS Nhà hàng Mobile — Danh sách bàn cột đơn, chạm để đặt món.
*@
@page "/pos/{ShopId:guid}/restaurant/mobile"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (_loadError)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu
        </div>
    }
    else
    {
        @* ═══ HEADER / TIÊU ĐỀ ═══ *@
        <div style="padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);display:flex;align-items:center;justify-content:space-between;">
            <span style="font-size:16px;font-weight:700;">Sơ đồ bàn</span>
            <span style="font-size:12px;color:var(--pos-text-tertiary);">@_tables.Count bàn</span>
        </div>

        @* ═══ SECTION FILTER / LỌC KHU VỰC ═══ *@
        <div class="pos-category-tabs" style="padding:8px 12px;">
            @foreach (var s in _sections)
            {
                <button class="pos-category-tab @(s == _activeSection ? "pos-category-tab--active" : "")"
                        style="font-size:12px;padding:6px 12px;" @onclick="() => _activeSection = s">@s</button>
            }
        </div>

        @* ═══ TABLE LIST / DANH SÁCH BÀN ═══ *@
        <div style="flex:1;overflow-y:auto;padding:8px 12px;display:flex;flex-direction:column;gap:8px;">
            @foreach (var t in FilteredTables)
            {
                var effectiveStatus = GetEffectiveStatus(t);
                var hasReservation = GetTableReservation(t) is not null;
                <div @onclick="() => OpenTable(t)"
                     style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px 16px;
                            display:flex;align-items:center;gap:12px;cursor:pointer;
                            border-left:4px solid @StatusColor(effectiveStatus);">
                    @* EN: Table number badge / VI: Badge số bàn *@
                    <div style="width:44px;height:44px;border-radius:10px;background:@StatusBg(effectiveStatus);
                                display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:700;">
                        @t.Number
                    </div>
                    <div style="flex:1;">
                        <div style="font-size:14px;font-weight:600;">@t.Name</div>
                        <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:2px;">
                            @t.Seats chỗ · @t.Section
                        </div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:11px;font-weight:600;color:@StatusColor(effectiveStatus);">
                            @StatusLabel(effectiveStatus)
                        </div>
                        @if (HasPendingOrder(t))
                        {
                            <div style="font-size:13px;font-weight:700;color:var(--pos-orange-primary);margin-top:2px;">
                                @FormatPrice(GetTableOrderTotal(t))
                            </div>
                        }
                        @if (hasReservation)
                        {
                            var res = GetTableReservation(t)!;
                            <div style="font-size:10px;color:var(--pos-info);margin-top:2px;font-weight:600;">
                                Đặt @res.ReservationTime.ToString("HH:mm")
                            </div>
                        }
                    </div>
                    <i data-lucide="chevron-right" style="color:var(--pos-text-tertiary);width:16px;"></i>
                </div>
            }
        </div>

        @* ═══ BOTTOM STATS / THỐNG KÊ DƯỚI ═══ *@
        <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);display:flex;justify-content:space-around;
                    background:var(--pos-bg-elevated);font-size:12px;">
            <div style="text-align:center;">
                <div style="font-weight:700;font-size:16px;color:var(--pos-success);">@_tables.Count(t => GetEffectiveStatus(t) == "available")</div>
                <div style="color:var(--pos-text-tertiary);">Trống</div>
            </div>
            <div style="text-align:center;">
                <div style="font-weight:700;font-size:16px;color:var(--pos-orange-primary);">@_tables.Count(t => GetEffectiveStatus(t) == "occupied")</div>
                <div style="color:var(--pos-text-tertiary);">Đang phục vụ</div>
            </div>
            <div style="text-align:center;">
                <div style="font-weight:700;font-size:16px;color:var(--pos-info);">@_tables.Count(t => GetEffectiveStatus(t) == "reserved")</div>
                <div style="color:var(--pos-text-tertiary);">Đã đặt</div>
            </div>
        </div>
    }
</div>

@code {

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

    // EN: Active section filter / VI: Bộ lọc khu vực
    private string _activeSection = "Tất cả";
    private string[] _sections = { "Tất cả" };

    // EN: Table data from API / VI: Dữ liệu bàn từ API
    private List<MobileTable> _tables = new();

    // EN: Active table orders from DB / VI: Đơn hàng active từ DB
    private readonly Dictionary<string, List<OrderItem>> _tableOrderMap = new();

    // EN: Reservations / VI: Đặt bàn
    private List<WebClientTpos.Client.Services.PosDataService.ReservationInfo> _reservations = new();

    private IEnumerable<MobileTable> FilteredTables =>
        _activeSection == "Tất cả" ? _tables : _tables.Where(t => t.Section == _activeSection);

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

        try
        {
            var tablesTask = DataService.GetTablesAsync(ShopId);
            var ordersTask = DataService.GetActiveTableOrdersAsync(ShopId);
            var reservationsTask = DataService.GetReservationsAsync(ShopId, DateTime.Today.ToString("yyyy-MM-dd"));
            await Task.WhenAll(tablesTask, ordersTask, reservationsTask);

            var apiTables = await tablesTask;
            var activeOrders = await ordersTask;
            _reservations = await reservationsTask;

            _tables = apiTables.Select(t => new MobileTable(
                t.Id.ToString(),
                int.TryParse(t.TableNumber, out var num) ? num : 0,
                $"Bàn {t.TableNumber}",
                t.Capacity,
                t.Status ?? "available",
                t.Zone ?? "Trong nhà"
            )).ToList();

            // EN: Build order map per table / VI: Tạo map đơn theo bàn
            foreach (var order in activeOrders)
            {
                if (order.TableId == null) continue;
                var tableKey = order.TableId.Value.ToString();
                if (!_tableOrderMap.ContainsKey(tableKey))
                    _tableOrderMap[tableKey] = new();
                foreach (var item in order.Items)
                {
                    var existing = _tableOrderMap[tableKey].FirstOrDefault(i => i.ProductId == item.ProductId);
                    if (existing != null)
                        existing.Qty += item.Quantity;
                    else
                        _tableOrderMap[tableKey].Add(new OrderItem(item.ProductId, item.ProductName, item.UnitPrice, item.Quantity));
                }
            }

            var zones = _tables.Select(t => t.Section).Distinct().ToList();
            _sections = new[] { "Tất cả" }.Concat(zones).ToArray();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void OpenTable(MobileTable t) => NavigateTo("restaurant/waiter-pad");

    // ═══ TABLE ORDER HELPERS (synced with Desktop) ═══
    private bool HasPendingOrder(MobileTable table) =>
        _tableOrderMap.ContainsKey(table.Id) && _tableOrderMap[table.Id].Any();

    private decimal GetTableOrderTotal(MobileTable table) =>
        _tableOrderMap.TryGetValue(table.Id, out var items) ? items.Sum(i => i.Price * i.Qty) : 0;

    // ═══ RESERVATION HELPERS (synced with Desktop) ═══
    private WebClientTpos.Client.Services.PosDataService.ReservationInfo? GetTableReservation(MobileTable table)
    {
        if (!Guid.TryParse(table.Id, out var tableGuid)) return null;
        var now = DateTime.Now;
        return _reservations.FirstOrDefault(r =>
            r.TableId == tableGuid &&
            r.Status is "confirmed" or "pending" &&
            Math.Abs((r.ReservationTime - now).TotalHours) < 2);
    }

    private string GetEffectiveStatus(MobileTable table)
    {
        if (HasPendingOrder(table)) return "occupied";
        if (GetTableReservation(table) != null) return "reserved";
        return table.Status;
    }

    private static string StatusColor(string s) => s switch
    {
        "available" => "var(--pos-success)", "occupied" => "var(--pos-orange-primary)",
        "reserved" => "var(--pos-info)", _ => "var(--pos-text-tertiary)"
    };

    private static string StatusBg(string s) => s switch
    {
        "available" => "rgba(34,197,94,.15)", "occupied" => "rgba(255,92,0,.18)",
        "reserved" => "rgba(59,130,246,.18)", _ => "var(--pos-bg-interactive)"
    };

    private static string StatusLabel(string s) => s switch
    {
        "available" => "Trống", "occupied" => "Đang phục vụ", "reserved" => "Đã đặt", _ => s
    };

    private record MobileTable(string Id, int Number, string Name, int Seats, string Status, string Section);
    private class OrderItem(Guid productId, string name, decimal price, int qty)
    {
        public Guid ProductId { get; } = productId;
        public string Name { get; } = name;
        public decimal Price { get; } = price;
        public int Qty { get; set; } = qty;
    }
}
