@*
    EN: Karaoke Service Display — Room service call queue, request type, timestamp, status.
    VI: Hiển thị yêu cầu phục vụ Karaoke — Hàng đợi gọi phục vụ phòng, loại yêu cầu, thời gian, trạng thái.
*@
@page "/pos/{ShopId:guid}/karaoke/service-display"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService
@implements IDisposable

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER / TIÊU ĐỀ ═══ *@
    <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;
                border-bottom:1px solid var(--pos-border-subtle);flex-shrink:0;">
        <div style="display:flex;align-items:center;gap:12px;">
            <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>
            <span style="font-size:16px;font-weight:700;">Yêu cầu phục vụ</span>
            <span style="font-size:12px;padding:3px 10px;border-radius:6px;font-weight:600;
                         background:rgba(239,68,68,.15);color:#EF4444;">
                @_requests.Count(r => r.Status == "pending") chờ xử lý
            </span>
        </div>

        @* EN: Filter tabs / VI: Tab lọc *@
        <div style="display:flex;gap:6px;">
            @foreach (var filter in _filters)
            {
                <button style="padding:6px 14px;border-radius:8px;font-size:12px;cursor:pointer;border:none;
                               background:@(filter == _activeFilter ? "var(--pos-orange-primary)" : "var(--pos-bg-interactive)");
                               color:@(filter == _activeFilter ? "#FFF" : "var(--pos-text-secondary)");"
                        @onclick="() => _activeFilter = filter">
                    @filter
                </button>
            }
        </div>
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu
        </div>
    }
    else
    {
    @* ═══ SERVICE QUEUE / HÀNG ĐỢI PHỤC VỤ ═══ *@
    <div style="flex:1;overflow-y:auto;padding:16px;">
        @* EN: Summary cards / VI: Thẻ tóm tắt *@
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px;">
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;text-align:center;">
                <div style="font-size:24px;font-weight:700;color:#EF4444;">@_requests.Count(r => r.Status == "pending")</div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:4px;">Chờ xử lý</div>
            </div>
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;text-align:center;">
                <div style="font-size:24px;font-weight:700;color:var(--pos-orange-primary);">@_requests.Count(r => r.Status == "processing")</div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:4px;">Đang xử lý</div>
            </div>
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;text-align:center;">
                <div style="font-size:24px;font-weight:700;color:#22C55E;">@_requests.Count(r => r.Status == "completed")</div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:4px;">Hoàn thành</div>
            </div>
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;text-align:center;">
                <div style="font-size:24px;font-weight:700;">@_requests.Count</div>
                <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:4px;">Tổng hôm nay</div>
            </div>
        </div>

        @* ═══ REQUEST LIST / DANH SÁCH YÊU CẦU ═══ *@
        <div style="display:flex;flex-direction:column;gap:8px;">
            @foreach (var req in FilteredRequests)
            {
                <div style="display:flex;align-items:center;gap:14px;padding:14px 16px;
                            background:var(--pos-bg-elevated);border-radius:var(--pos-radius);
                            border-left:4px solid @GetTypeBorderColor(req.Type);
                            border:1px solid @(req.Status == "pending" ? "rgba(239,68,68,.3)" : "var(--pos-border-subtle)");">
                    @* EN: Type icon / VI: Icon loại *@
                    <div style="width:44px;height:44px;border-radius:12px;background:@GetTypeBg(req.Type);
                                display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i data-lucide="@GetTypeIcon(req.Type)" style="width:20px;height:20px;color:@GetTypeFg(req.Type);"></i>
                    </div>

                    @* EN: Request info / VI: Thông tin yêu cầu *@
                    <div style="flex:1;min-width:0;">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <span style="font-size:15px;font-weight:700;">@req.Room</span>
                            <span style="font-size:11px;padding:2px 8px;border-radius:5px;font-weight:600;
                                         background:@GetTypeBg(req.Type);color:@GetTypeFg(req.Type);">@req.Type</span>
                        </div>
                        <div style="font-size:13px;color:var(--pos-text-secondary);margin-top:2px;">@req.Description</div>
                    </div>

                    @* EN: Timestamp / VI: Thời gian *@
                    <div style="text-align:right;flex-shrink:0;">
                        <div style="font-size:12px;color:var(--pos-text-tertiary);">@req.Time</div>
                        <div style="font-size:11px;color:@(req.Status == "pending" ? "#EF4444" : "var(--pos-text-tertiary)");margin-top:2px;">
                            @req.Elapsed
                        </div>
                    </div>

                    @* EN: Status + action / VI: Trạng thái + hành động *@
                    <div style="flex-shrink:0;">
                        @if (req.Status == "pending")
                        {
                            <button style="padding:8px 14px;border-radius:8px;background:var(--pos-orange-primary);
                                           border:none;color:#FFF;cursor:pointer;font-size:12px;font-weight:600;"
                                    @onclick="@(() => UpdateRequestStatus(req, "processing"))">
                                Nhận
                            </button>
                        }
                        else if (req.Status == "processing")
                        {
                            <button style="padding:8px 14px;border-radius:8px;background:rgba(34,197,94,.15);
                                           border:none;color:#22C55E;cursor:pointer;font-size:12px;font-weight:600;"
                                    @onclick="@(() => UpdateRequestStatus(req, "completed"))">
                                Xong
                            </button>
                        }
                        else
                        {
                            <span style="font-size:12px;color:#22C55E;font-weight:600;">
                                <i data-lucide="check-circle" style="width:16px;height:16px;display:inline;"></i>
                            </span>
                        }
                    </div>
                </div>
            }
        </div>
    </div>
    }
</div>

@code {

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

    // EN: Filter / VI: Bộ lọc
    private string _activeFilter = "Tất cả";
    private readonly string[] _filters = { "Tất cả", "Chờ xử lý", "Đang xử lý", "Hoàn thành" };

    // EN: Room lookup map (tableId → roomName) loaded from DB / VI: Map tra cứu phòng (tableId → tên phòng) từ DB
    private Dictionary<Guid, string> _roomLookup = new();

    // EN: Service requests mapped from kitchen tickets / VI: Yêu cầu phục vụ map từ kitchen tickets
    private List<ServiceRequest> _requests = new();

    // EN: Auto-refresh timer (15s) / VI: Timer tự động refresh (15 giây)
    private Timer? _refreshTimer;

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

        // EN: Auto-refresh every 15 seconds / VI: Tự động refresh mỗi 15 giây
        _refreshTimer = new Timer(async _ =>
        {
            await LoadDataAsync();
            await InvokeAsync(StateHasChanged);
        }, null, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
    }

    private async Task LoadDataAsync()
    {
        try
        {
            // EN: Load tables for room name lookup and all ticket statuses in parallel
            // VI: Tải danh sách phòng và tất cả trạng thái ticket song song
            var tablesTask = DataService.GetTablesAsync(ShopId);
            var pendingTask = DataService.GetKitchenTicketsAsync(ShopId, "Pending");
            var processingTask = DataService.GetKitchenTicketsAsync(ShopId, "InProgress");
            var completedTask = DataService.GetKitchenTicketsAsync(ShopId, "Completed");

            await Task.WhenAll(tablesTask, pendingTask, processingTask, completedTask);

            var tables = await tablesTask;
            _roomLookup = tables.ToDictionary(t => t.Id, t => t.TableNumber);

            var allTickets = new List<WebClientTpos.Client.Services.PosDataService.KitchenTicketInfo>();
            allTickets.AddRange(await pendingTask);
            allTickets.AddRange(await processingTask);
            allTickets.AddRange(await completedTask);

            // EN: Map kitchen tickets to ServiceRequest display model
            // VI: Map kitchen tickets sang model hiển thị ServiceRequest
            _requests = allTickets.OrderByDescending(t => t.CreatedAt).Select(t =>
            {
                var roomName = _roomLookup.TryGetValue(t.SessionId, out var name) ? name : t.SessionId.ToString()[..8];
                var elapsed = DateTime.UtcNow - t.CreatedAt;
                var elapsedStr = elapsed.TotalMinutes < 60
                    ? $"{(int)elapsed.TotalMinutes} phút trước"
                    : $"{(int)elapsed.TotalHours}h{elapsed.Minutes:D2} trước";

                var status = t.Status switch
                {
                    "Pending" => "pending",
                    "InProgress" => "processing",
                    "Completed" => "completed",
                    _ => "pending"
                };

                var type = t.Station switch
                {
                    "Kitchen" or "Bar" => "F&B",
                    "Technical" => "Kỹ thuật",
                    "Cleaning" => "Dọn dẹp",
                    _ => "F&B"
                };

                return new ServiceRequest(
                    t.Id,
                    roomName,
                    type,
                    t.ItemName ?? "Yêu cầu phục vụ",
                    t.CreatedAt.ToLocalTime().ToString("HH:mm"),
                    elapsedStr,
                    status
                );
            }).ToList();
        }
        catch
        {
            _loadError = _requests.Count == 0;
        }
        finally
        {
            _isLoading = false;
        }
    }

    /// <summary>
    /// EN: Update ticket status via API when user clicks Nhận/Xong buttons.
    /// VI: Cập nhật trạng thái ticket qua API khi user nhấn nút Nhận/Xong.
    /// </summary>
    private async Task UpdateRequestStatus(ServiceRequest req, string newStatus)
    {
        var apiStatus = newStatus switch
        {
            "processing" => "InProgress",
            "completed" => "Completed",
            _ => newStatus
        };

        var success = await DataService.UpdateTicketStatusAsync(req.TicketId,
            new WebClientTpos.Client.Services.PosDataService.UpdateTicketStatusRequest(apiStatus));

        if (success)
        {
            req.Status = newStatus;
        }
    }

    private IEnumerable<ServiceRequest> FilteredRequests => _activeFilter switch
    {
        "Chờ xử lý" => _requests.Where(r => r.Status == "pending"),
        "Đang xử lý" => _requests.Where(r => r.Status == "processing"),
        "Hoàn thành" => _requests.Where(r => r.Status == "completed"),
        _ => _requests
    };

    private static string GetTypeIcon(string t) => t switch
    {
        "F&B" => "utensils", "Kỹ thuật" => "wrench", "Dọn dẹp" => "sparkles", _ => "bell"
    };

    private static string GetTypeBg(string t) => t switch
    {
        "F&B" => "rgba(255,92,0,.15)", "Kỹ thuật" => "rgba(59,130,246,.15)",
        "Dọn dẹp" => "rgba(245,158,11,.15)", _ => "var(--pos-bg-interactive)"
    };

    private static string GetTypeFg(string t) => t switch
    {
        "F&B" => "#FF5C00", "Kỹ thuật" => "#3B82F6", "Dọn dẹp" => "#F59E0B", _ => "#ADADB0"
    };

    private static string GetTypeBorderColor(string t) => t switch
    {
        "F&B" => "#FF5C00", "Kỹ thuật" => "#3B82F6", "Dọn dẹp" => "#F59E0B", _ => "var(--pos-border-default)"
    };

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

    private class ServiceRequest(Guid ticketId, string room, string type, string description, string time, string elapsed, string status)
    {
        public Guid TicketId { get; set; } = ticketId;
        public string Room { get; set; } = room;
        public string Type { get; set; } = type;
        public string Description { get; set; } = description;
        public string Time { get; set; } = time;
        public string Elapsed { get; set; } = elapsed;
        public string Status { get; set; } = status;
    }
}
