@*
    EN: Table Select — Quick table selection for seating guests with capacity matching.
    VI: Chọn bàn nhanh — Chọn bàn nhanh cho khách với kiểm tra sức chứa.
*@
@page "/pos/{ShopId:guid}/restaurant/table-select"
@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="armchair" style="width:18px;height:18px;display:inline;"></i> Chọn bàn
        </span>
    </div>

    @* ═══ GUEST COUNT + SECTION FILTER / SỐ KHÁCH + LỌC KHU VỰC ═══ *@
    <div style="padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);display:flex;align-items:center;gap:16px;">
        @* EN: Guest count input / VI: Nhập số khách *@
        <div style="display:flex;align-items:center;gap:8px;">
            <i data-lucide="users" style="width:16px;height:16px;color:var(--pos-text-tertiary);"></i>
            <span style="font-size:13px;color:var(--pos-text-secondary);">Số khách:</span>
            <div style="display:flex;align-items:center;gap:4px;">
                <button style="width:32px;height:32px;border-radius:8px;border:1px solid var(--pos-border-default);
                               background:var(--pos-bg-interactive);color:var(--pos-text-primary);cursor:pointer;font-size:16px;font-weight:700;"
                        @onclick="() => { if (_guestCount > 1) _guestCount--; }">−</button>
                <span style="width:32px;text-align:center;font-size:18px;font-weight:700;">@_guestCount</span>
                <button style="width:32px;height:32px;border-radius:8px;border:1px solid var(--pos-border-default);
                               background:var(--pos-bg-interactive);color:var(--pos-text-primary);cursor:pointer;font-size:16px;font-weight:700;"
                        @onclick="() => _guestCount++">+</button>
            </div>
        </div>

        @* EN: Section filter / VI: Lọc khu vực *@
        <div class="pos-category-tabs" style="padding:0;flex:1;">
            @foreach (var sec in _sections)
            {
                <button class="pos-category-tab @(sec == _activeSection ? "pos-category-tab--active" : "")"
                        style="font-size:12px;padding:6px 12px;" @onclick="() => _activeSection = sec">@sec</button>
            }
        </div>
    </div>

    @* ═══ TABLE GRID / LƯỚI BÀ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(140px,1fr));gap:12px;">
            @foreach (var table in FilteredTables)
            {
                var matchColor = CapacityColor(table.Seats, _guestCount);
                var isSelected = _selectedTable == table.Id;

                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:18px;
                            text-align:center;cursor:pointer;transition:all .2s ease;
                            border:2px solid @(isSelected ? "var(--pos-orange-primary)" : "transparent");"
                     @onclick="() => _selectedTable = table.Id">
                    @* EN: Capacity indicator / VI: Chỉ báo sức chứa *@
                    <div style="width:12px;height:12px;border-radius:50%;background:@matchColor;margin:0 auto 8px;"></div>
                    <div style="font-size:22px;font-weight:800;">@table.Name</div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:6px;">
                        <i data-lucide="users" style="width:12px;height:12px;display:inline;"></i> @table.Seats chỗ
                    </div>
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">@table.Section</div>

                    @if (isSelected)
                    {
                        <div style="margin-top:8px;width:24px;height:24px;border-radius:50%;background:var(--pos-orange-primary);
                                    display:flex;align-items:center;justify-content:center;margin-left:auto;margin-right:auto;">
                            <i data-lucide="check" style="width:14px;height:14px;color:#fff;"></i>
                        </div>
                    }
                </div>
            }
        </div>

        @if (!FilteredTables.Any())
        {
            <div style="text-align:center;padding:40px;color:var(--pos-text-tertiary);">
                <i data-lucide="search-x" style="width:40px;height:40px;display:block;margin:0 auto 12px;"></i>
                <div style="font-size:14px;">Không tìm thấy bàn trống phù hợp</div>
            </div>
        }
        }
    </div>

    @* ═══ SELECTED TABLE INFO / THÔNG TIN BÀN ĐÃ CHỌN ═══ *@
    @if (_selectedTable is not null)
    {
        var sel = _availableTables.First(t => t.Id == _selectedTable);
        <div style="padding:10px 16px;background:var(--pos-bg-elevated);border-top:1px solid var(--pos-border-subtle);
                    display:flex;align-items:center;gap:16px;">
            <div style="display:flex;align-items:center;gap:8px;">
                <span style="font-size:14px;font-weight:700;">@sel.Name</span>
                <span style="font-size:12px;color:var(--pos-text-tertiary);">@sel.Seats chỗ · @sel.Section</span>
            </div>
            <span style="flex:1;"></span>
            <div style="width:10px;height:10px;border-radius:50%;background:@CapacityColor(sel.Seats, _guestCount);"></div>
            <span style="font-size:12px;color:var(--pos-text-secondary);">
                @CapacityLabel(sel.Seats, _guestCount)
            </span>
        </div>
    }

    @* ═══ FOOTER ACTIONS / NÚT HÀNH ĐỘNG ═══ *@
    <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);display:flex;gap:8px;flex-shrink:0;">
        <button style="flex:1;padding:12px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);
                       border:1px solid var(--pos-border-default);color:var(--pos-text-primary);cursor:pointer;font-size:13px;"
                @onclick="@(() => NavigateTo("restaurant"))">
            Hủy
        </button>
        <button class="pos-btn-checkout" style="flex:2;" @onclick="OpenTable"
                disabled="@(_selectedTable is null)">
            <i data-lucide="door-open" style="width:14px;height:14px;display:inline;"></i> Mở bàn
        </button>
    </div>
</div>

@code {

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

    private int _guestCount = 4;
    private string _activeSection = "Tất cả";
    private string? _selectedTable;
    private string[] _sections = { "Tất cả" };

    // EN: Available tables from API / VI: Bàn trống từ API
    private List<AvailableTable> _availableTables = new();

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

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

        try
        {
            var apiTables = await DataService.GetTablesAsync(ShopId);

            _availableTables = apiTables
                .Where(t => (t.Status ?? "available") == "available")
                .Select(t => new AvailableTable(
                    t.Id.ToString(),
                    $"Bàn {t.TableNumber}",
                    t.Capacity,
                    t.Zone ?? "Tầng 1"
                )).ToList();

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

    private static string CapacityColor(int seats, int guests) =>
        seats >= guests + 2 ? "var(--pos-success)"
        : seats >= guests ? "#F59E0B"
        : "var(--pos-text-tertiary)";

    private static string CapacityLabel(int seats, int guests) =>
        seats >= guests + 2 ? "Rộng rãi"
        : seats >= guests ? "Vừa"
        : "Quá nhỏ";

    private void OpenTable() => NavigateTo("restaurant");

    private record AvailableTable(string Id, string Name, int Seats, string Section);
}
