@*
    EN: Karaoke POS Desktop — Room map grid + session panel for karaoke room management.
        Rooms loaded from DB via DataService.GetTablesAsync. Active orders loaded for occupied rooms.
    VI: POS Karaoke Desktop — Lưới sơ đồ phòng + panel phiên hát cho quản lý phòng karaoke.
        Phòng tải từ DB qua DataService.GetTablesAsync. Đơn hàng active tải cho phòng đang sử dụng.
*@
@page "/pos/{ShopId:guid}/karaoke"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

@* ═══ ROOM MAP PANEL (LEFT) / PANEL SƠ ĐỒ PHÒNG (TRÁI) ═══ *@
<div class="pos-product-panel" style="padding:16px;overflow-y:auto;">
    @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
    {
    @* EN: Floor/zone tabs / VI: Tab tầng/khu vực *@
    <div class="pos-category-tabs">
        @foreach (var zone in _zones)
        {
            <button class="pos-category-tab @(zone == _activeZone ? "pos-category-tab--active" : "")"
                    @onclick="() => _activeZone = zone">
                @zone
            </button>
        }
    </div>

    @* ═══ ROOM GRID / LƯỚI PHÒNG ═══ *@
    @if (!_rooms.Any())
    {
        <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:60px 0;color:var(--pos-text-tertiary);">
            <i data-lucide="door-open" style="width:48px;height:48px;margin-bottom:12px;opacity:0.3;"></i>
            <div style="font-size:15px;font-weight:600;margin-bottom:4px;">Chưa có phòng nào</div>
            <div style="font-size:13px;">Vui lòng thêm phòng trong phần Quản lý cửa hàng</div>
        </div>
    }
    else
    {
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:12px;padding:8px 0;">
        @foreach (var room in FilteredRooms)
        {
            <div @onclick="() => SelectRoom(room)"
                 style="background:@GetStatusColor(room.Status);border-radius:var(--pos-radius);
                        padding:16px;text-align:center;cursor:pointer;
                        border:2px solid @(SelectedRoom?.Id == room.Id ? "var(--pos-orange-primary)" : "transparent");
                        transition:all .2s ease;">
                <div style="font-size:11px;font-weight:600;color:rgba(255,255,255,.6);margin-bottom:4px;">
                    @room.Type
                </div>
                <div style="font-size:20px;font-weight:700;">@room.Name</div>
                <div style="font-size:12px;color:rgba(255,255,255,.7);margin-top:4px;">
                    <i data-lucide="users" style="width:12px;height:12px;display:inline;"></i> @room.Capacity người
                </div>
                <div style="font-size:11px;margin-top:6px;font-weight:600;text-transform:uppercase;">
                    @GetStatusLabel(room.Status)
                </div>
                @if (room.Status == "occupied" && room.SessionStart.HasValue)
                {
                    <div style="font-size:11px;margin-top:4px;color:rgba(255,255,255,.5);">
                        <i data-lucide="clock" style="width:10px;height:10px;display:inline;"></i>
                        @((DateTime.Now - room.SessionStart.Value).ToString(@"hh\:mm"))
                    </div>
                }
            </div>
        }
    </div>
    }
    }
</div>

@* ═══ SESSION PANEL (RIGHT) / PANEL PHIÊN HÁT (PHẢI) ═══ *@
<div class="pos-cart-panel">
    @if (SelectedRoom is not null)
    {
        <div class="pos-cart-header">
            <span class="pos-cart-header__title">@SelectedRoom.Name</span>
            <span style="font-size:12px;color:var(--pos-text-tertiary);">@SelectedRoom.Type • @SelectedRoom.Capacity người</span>
        </div>

        <div class="pos-cart-items">
            @if (SelectedRoom.Status == "occupied")
            {
                @* EN: Session timer / VI: Đồng hồ phiên *@
                <div style="text-align:center;padding:16px;">
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">THỜI GIAN SỬ DỤNG</div>
                    <div style="font-size:32px;font-weight:700;color:var(--pos-orange-primary);">
                        @if (SelectedRoom.SessionStart.HasValue)
                        {
                            @((DateTime.Now - SelectedRoom.SessionStart.Value).ToString(@"hh\:mm\:ss"))
                        }
                        else
                        {
                            <text>--:--:--</text>
                        }
                    </div>
                </div>

                @* EN: F&B orders from DB / VI: Đơn F&B từ DB *@
                <div style="padding:0 8px;">
                    <div style="font-size:12px;color:var(--pos-text-tertiary);padding:8px 0;font-weight:600;">ĐƠN F&B</div>
                    @{ var roomOrders = _activeOrders.Where(o => o.TableId.ToString() == SelectedRoom.Id).ToList(); }
                    @if (roomOrders.Any())
                    {
                        @foreach (var order in roomOrders)
                        {
                            @foreach (var item in order.Items)
                            {
                                <div class="pos-cart-item">
                                    <div class="pos-cart-item__info">
                                        <span class="pos-cart-item__name">@item.ProductName</span>
                                        <span class="pos-cart-item__price">@FormatPrice(item.UnitPrice)</span>
                                    </div>
                                    <span style="font-size:13px;font-weight:600;">x@item.Quantity</span>
                                </div>
                            }
                        }
                    }
                    else
                    {
                        <div style="text-align:center;padding:12px;color:var(--pos-text-tertiary);font-size:12px;">
                            Chưa có đơn F&B
                        </div>
                    }
                </div>
            }
            else
            {
                <div style="text-align:center;padding:32px 16px;color:var(--pos-text-tertiary);font-size:13px;">
                    Phòng trống — Nhấn để mở phiên mới
                </div>
            }
        </div>

        <div class="pos-cart-footer">
            @{
                var totalFnb = _activeOrders
                    .Where(o => o.TableId.ToString() == SelectedRoom?.Id)
                    .Sum(o => o.TotalAmount);
                var roomCost = 0m;
                if (SelectedRoom!.HourlyRate > 0 && SelectedRoom.SessionStart.HasValue)
                {
                    var elapsed = DateTime.Now - SelectedRoom.SessionStart.Value;
                    roomCost = Math.Ceiling((decimal)elapsed.TotalMinutes / 60m) * SelectedRoom.HourlyRate;
                }
            }
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:4px;">
                <span style="color:var(--pos-text-secondary);">Tiền phòng</span>
                <span>@FormatPrice(roomCost)</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:8px;">
                <span style="color:var(--pos-text-secondary);">Tiền F&B</span>
                <span>@FormatPrice(totalFnb)</span>
            </div>
            <div class="pos-cart-total">
                <span class="pos-cart-total__label">Tổng cộng</span>
                <span class="pos-cart-total__value">@FormatPrice(roomCost + totalFnb)</span>
            </div>
            @if (SelectedRoom.Status == "available")
            {
                <button class="pos-btn-checkout" @onclick="@(() => NavigateTo("karaoke/room-select"))">
                    <i data-lucide="play" style="width:18px;height:18px;"></i> Mở phiên
                </button>
            }
            else if (SelectedRoom.Status == "occupied")
            {
                <button class="pos-btn-checkout" @onclick="@(() => NavigateTo($"karaoke/room-session/{SelectedRoom.Id}"))">
                    <i data-lucide="receipt" style="width:18px;height:18px;"></i> Xem chi tiết
                </button>
            }
        </div>
    }
    else
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);font-size:14px;">
            Chọn phòng để bắt đầu
        </div>
    }
</div>

@code {

    private bool _isLoading = true;
    private bool _loadError;

    private string _activeZone = "Tất cả";
    private string[] _zones = { "Tất cả" };

    private RoomInfo? SelectedRoom { get; set; }

    private List<RoomInfo> _rooms = new();
    private List<WebClientTpos.Client.Services.PosDataService.ActiveTableOrderDto> _activeOrders = new();

    private IEnumerable<RoomInfo> FilteredRooms =>
        _activeZone == "Tất cả" ? _rooms : _rooms.Where(r => r.Zone == _activeZone);

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

        try
        {
            var tablesTask = DataService.GetTablesAsync(ShopId);
            var ordersTask = DataService.GetActiveTableOrdersAsync(ShopId);
            await Task.WhenAll(tablesTask, ordersTask);

            var tables = await tablesTask;
            _activeOrders = await ordersTask;

            _rooms = tables.Select(t => new RoomInfo(
                t.Id.ToString(),
                t.TableNumber,
                t.Capacity,
                t.Status,
                t.Zone ?? "Standard",
                t.Zone ?? "Tầng 1",
                t.StartedAt,
                t.HourlyRate
            )).ToList();

            var zoneNames = _rooms.Select(r => r.Zone).Distinct().ToList();
            _zones = new[] { "Tất cả" }.Concat(zoneNames).ToArray();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void SelectRoom(RoomInfo room) => SelectedRoom = room;

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

    private static string GetStatusLabel(string status) => status switch
    {
        "available" => "Trống", "occupied" => "Đang hát",
        "reserved" => "Đã đặt", "cleaning" => "Đang dọn", _ => status
    };

    private record RoomInfo(string Id, string Name, int Capacity, string Status, string Type, string Zone, DateTime? SessionStart, decimal HourlyRate = 0);
}
