@*
    EN: Karaoke Room Session — Active room timer, F&B orders from DB, extend/end session via API.
    VI: Phiên phòng Karaoke — Đồng hồ phòng, đơn F&B từ DB, gia hạn/kết thúc phiên qua API.
*@
@page "/pos/{ShopId:guid}/karaoke/room-session/{RoomId:guid}"
@layout PosLayout
@inherits PosBase
@implements IDisposable
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;overflow:hidden;">
    @* ═══ SESSION DETAILS (LEFT) / CHI TIẾT PHIÊN (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 phòng
            </div>
        }
        else
        {
        @* EN: Back + Room header / VI: Quay lại + Tiêu đề phòng *@
        <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
            <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"))">
                <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
            </button>
            <div>
                <div style="font-size:18px;font-weight:700;">@_room?.Name</div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);">@_room?.Type • @_room?.Capacity người • @_room?.Zone</div>
            </div>
        </div>

        @* ═══ TIMER SECTION / KHU VỰC ĐỒNG HỒ ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:24px;
                    text-align:center;margin-bottom:16px;">
            <div style="font-size:12px;color:var(--pos-text-tertiary);font-weight:600;margin-bottom:8px;">
                THỜI GIAN SỬ DỤNG
            </div>
            <div style="font-size:48px;font-weight:700;color:var(--pos-orange-primary);font-variant-numeric:tabular-nums;">
                @_elapsed.ToString(@"hh\:mm\:ss")
            </div>
            @if (_room?.SessionStart != null)
            {
                <div style="display:flex;justify-content:center;gap:24px;margin-top:12px;font-size:13px;color:var(--pos-text-secondary);">
                    <span>Bắt đầu: <b>@_room.SessionStart.Value.ToLocalTime().ToString("HH:mm")</b></span>
                </div>
            }
        </div>

        @* ═══ ROOM RATE / GIÁ PHÒNG ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;margin-bottom:16px;">
            <div style="font-size:13px;font-weight:600;margin-bottom:12px;">Giá phòng</div>
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                <span style="color:var(--pos-text-secondary);">Loại phòng</span>
                <span>@(_room?.Type ?? "-")</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                <span style="color:var(--pos-text-secondary);">Giá/giờ</span>
                <span>@FormatPrice(_room?.HourlyRate ?? 0)</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                <span style="color:var(--pos-text-secondary);">Thời gian</span>
                <span>@_elapsed.ToString(@"h\:mm") giờ</span>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:14px;font-weight:700;padding-top:8px;border-top:1px solid var(--pos-border-subtle);">
                <span>Tiền phòng</span>
                <span style="color:var(--pos-orange-primary);">@FormatPrice(RoomCost)</span>
            </div>
        </div>

        @* ═══ ACTION BUTTONS / NÚT HÀNH ĐỘNG ═══ *@
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;">
            <button style="padding:14px 8px;border-radius:var(--pos-radius);background:rgba(59,130,246,.15);
                           border:none;color:#3B82F6;cursor:pointer;font-size:13px;font-weight:500;"
                    @onclick="@(() => NavigateTo($"karaoke/room-extend/{RoomId}"))">
                <i data-lucide="clock" style="width:18px;height:18px;display:block;margin:0 auto 4px;"></i>
                Gia hạn
            </button>
            <button style="padding:14px 8px;border-radius:var(--pos-radius);background:rgba(34,197,94,.15);
                           border:none;color:#22C55E;cursor:pointer;font-size:13px;font-weight:500;"
                    @onclick="@(() => NavigateTo($"karaoke/order-fnb/{RoomId}"))">
                <i data-lucide="utensils" style="width:18px;height:18px;display:block;margin:0 auto 4px;"></i>
                Gọi F&B
            </button>
            <button style="padding:14px 8px;border-radius:var(--pos-radius);background:rgba(239,68,68,.15);
                           border:none;color:#EF4444;cursor:pointer;font-size:13px;font-weight:500;"
                    disabled="@_ending"
                    @onclick="EndSession">
                <i data-lucide="square" style="width:18px;height:18px;display:block;margin:0 auto 4px;"></i>
                @(_ending ? "Đang..." : "Kết thúc")
            </button>
        </div>

        @if (!string.IsNullOrEmpty(_errorMsg))
        {
            <div style="margin-top:12px;padding:10px;border-radius:8px;background:rgba(239,68,68,.15);color:#EF4444;font-size:13px;">
                @_errorMsg
            </div>
        }
        }
    </div>

    @* ═══ F&B ORDER PANEL (RIGHT) / PANEL ĐƠN F&B (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);">@_fnbItems.Count món</span>
        </div>

        <div class="pos-cart-items">
            @if (_fnbItems.Any())
            {
                @foreach (var item in _fnbItems)
                {
                    <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>
                        <span style="font-size:13px;font-weight:600;">x@item.Qty</span>
                    </div>
                }
            }
            else
            {
                <div style="text-align:center;padding:32px 16px;color:var(--pos-text-tertiary);font-size:13px;">
                    Chưa có đơn F&B
                </div>
            }
        </div>

        <div class="pos-cart-footer">
            <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                <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(FnbTotal)</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 + FnbTotal)</span>
            </div>
            <button class="pos-btn-checkout" @onclick="@(() => NavigateTo($"karaoke/order-fnb/{RoomId}"))">
                <i data-lucide="plus" style="width:18px;height:18px;"></i> Gọi thêm F&B
            </button>
        </div>
    </div>
</div>

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

    private bool _isLoading = true;
    private bool _loadError;
    private bool _ending;
    private string? _errorMsg;

    private RoomInfo? _room;
    private List<FnbItem> _fnbItems = new();
    private TimeSpan _elapsed;
    private System.Threading.Timer? _timer;

    private decimal RoomCost => (_room?.HourlyRate ?? 0) > 0
        ? Math.Ceiling((decimal)_elapsed.TotalMinutes / 60m) * _room!.HourlyRate
        : 0;
    private decimal FnbTotal => _fnbItems.Sum(i => i.Price * i.Qty);

    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;
            var table = tables.FirstOrDefault(t => t.Id == RoomId);
            if (table != null)
            {
                _room = new RoomInfo(table.Id, table.TableNumber, table.Capacity,
                    table.Zone ?? "Standard", table.Zone ?? "Tầng 1", table.StartedAt, table.HourlyRate);
            }
            else
            {
                _loadError = true;
                return;
            }

            // Load F&B orders for this room
            var allOrders = await ordersTask;
            var roomOrders = allOrders.Where(o => o.TableId == RoomId).ToList();
            _fnbItems = roomOrders
                .SelectMany(o => o.Items)
                .GroupBy(i => new { i.ProductName, i.UnitPrice })
                .Select(g => new FnbItem(g.Key.ProductName, g.Key.UnitPrice, g.Sum(i => i.Quantity)))
                .ToList();

            // Start timer
            if (_room.SessionStart.HasValue)
            {
                _elapsed = DateTime.Now - _room.SessionStart.Value;
                _timer = new System.Threading.Timer(_ =>
                {
                    _elapsed = DateTime.Now - _room.SessionStart!.Value;
                    InvokeAsync(StateHasChanged);
                }, null, 0, 1000);
            }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private async Task EndSession()
    {
        _ending = true;
        _errorMsg = null;
        try
        {
            await DataService.UpdateTableStatusAsync(RoomId, "cleaning");
            NavigateTo($"karaoke/room-reset/{RoomId}");
        }
        catch
        {
            _errorMsg = "Lỗi khi kết thúc phiên.";
            _ending = false;
        }
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }

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