@*
    EN: Kitchen Display System — Order tickets by status with timer and bump button.
    VI: Hệ thống hiển thị bếp — Phiếu đơn theo trạng thái với đồng hồ và nút hoàn thành.
*@
@page "/pos/{ShopId:guid}/restaurant/kitchen-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="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;">Màn hình bếp</span>
        <span style="flex:1;"></span>
        @* EN: Status legend / VI: Chú thích trạng thái *@
        <span style="font-size:11px;display:flex;gap:12px;">
            <span style="color:var(--pos-danger);">● Mới (@_tickets.Count(t => t.Status == "new"))</span>
            <span style="color:var(--pos-warning);">● Đang nấu (@_tickets.Count(t => t.Status == "cooking"))</span>
            <span style="color:var(--pos-success);">● Sẵn sàng (@_tickets.Count(t => t.Status == "ready"))</span>
        </span>
    </div>

    @* ═══ TICKET COLUMNS / CỘT PHIẾU ═══ *@
    @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
    {
    <div style="flex:1;display:flex;gap:16px;padding:16px;overflow-x:auto;">
        @foreach (var status in _statuses)
        {
            <div style="flex:1;min-width:280px;display:flex;flex-direction:column;gap:12px;">
                @* EN: Column header / VI: Tiêu đề cột *@
                <div style="padding:10px 14px;border-radius:var(--pos-radius);font-weight:700;font-size:14px;
                            background:@ColumnBg(status.Key);color:@ColumnColor(status.Key);text-align:center;">
                    @status.Value
                </div>

                @* EN: Tickets / VI: Phiếu *@
                <div style="flex:1;overflow-y:auto;display:flex;flex-direction:column;gap:10px;">
                    @foreach (var ticket in _tickets.Where(t => t.Status == status.Key))
                    {
                        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px;
                                    border-left:4px solid @ColumnColor(status.Key);">
                            @* EN: Ticket header / VI: Tiêu đề phiếu *@
                            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
                                <span style="font-weight:700;font-size:14px;">@ticket.Table</span>
                                <span style="font-size:12px;padding:3px 8px;border-radius:6px;font-weight:600;
                                            background:@TimerBg(ticket.Minutes);color:@TimerColor(ticket.Minutes);">
                                    @ticket.Minutes phút
                                </span>
                            </div>

                            @* EN: Items / VI: Các món *@
                            @foreach (var item in ticket.Items)
                            {
                                <div style="display:flex;justify-content:space-between;padding:4px 0;font-size:13px;
                                            border-bottom:1px solid var(--pos-border-subtle);">
                                    <span>@item.Qty x @item.Name</span>
                                    @if (!string.IsNullOrEmpty(item.Note))
                                    {
                                        <span style="color:var(--pos-warning);font-size:11px;font-style:italic;">@item.Note</span>
                                    }
                                </div>
                            }

                            @* EN: Bump button / VI: Nút chuyển trạng thái *@
                            <div style="margin-top:10px;">
                                @if (status.Key == "new")
                                {
                                    <button class="pos-btn-checkout" style="height:36px;font-size:13px;background:var(--pos-warning);"
                                            @onclick="@(() => UpdateStatus(ticket, "cooking"))">
                                        <i data-lucide="chef-hat" style="width:14px;"></i> Bắt đầu nấu
                                    </button>
                                }
                                else if (status.Key == "cooking")
                                {
                                    <button class="pos-btn-checkout" style="height:36px;font-size:13px;background:var(--pos-success);"
                                            @onclick="@(() => UpdateStatus(ticket, "ready"))">
                                        <i data-lucide="check" style="width:14px;"></i> Sẵn sàng
                                    </button>
                                }
                                else
                                {
                                    <button class="pos-btn-checkout" style="height:36px;font-size:13px;background:var(--pos-bg-interactive);color:var(--pos-text-secondary);"
                                            @onclick="@(() => UpdateStatus(ticket, "served"))">
                                        <i data-lucide="truck" style="width:14px;"></i> Đã mang ra
                                    </button>
                                }
                            </div>
                        </div>
                    }
                </div>
            </div>
        }
    </div>
    }
</div>

@code {

    // EN: Loading state / VI: Trạng thái tải
    private bool _isLoading = true;
    private bool _loadError;
    private System.Threading.Timer? _refreshTimer;

    private readonly Dictionary<string, string> _statuses = new()
    {
        ["new"] = "Mới", ["cooking"] = "Đang nấu", ["ready"] = "Sẵn sàng"
    };

    // EN: Kitchen tickets from API / VI: Phiếu bếp từ API
    private List<KitchenTicket> _tickets = new();

    // EN: Table lookup for mapping ticket to table name / VI: Tra cứu bàn để ánh xạ phiếu sang tên bàn
    private Dictionary<Guid, string> _tableLookup = new();

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

        try
        {
            // EN: Load tables for lookup / VI: Tải bàn để tra cứu
            var tables = await DataService.GetTablesAsync(ShopId);
            _tableLookup = tables.ToDictionary(t => t.Id, t => $"Bàn {t.TableNumber}");

            // EN: Fetch tickets by status in parallel / VI: Tải phiếu theo trạng thái song song
            await LoadTicketsAsync();

            // EN: Auto-refresh every 10 seconds / VI: Tự động làm mới mỗi 10 giây
            _refreshTimer = new System.Threading.Timer(async _ =>
            {
                try
                {
                    await LoadTicketsAsync();
                    await InvokeAsync(StateHasChanged);
                }
                catch { /* silently ignore refresh errors */ }
            }, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private async Task LoadTicketsAsync()
    {
        // EN: Fetch Pending, InProgress, and Completed tickets in parallel
        // VI: Tải phiếu Pending, InProgress, và Completed song song
        var pendingTask = DataService.GetKitchenTicketsAsync(ShopId, "Pending");
        var inProgressTask = DataService.GetKitchenTicketsAsync(ShopId, "InProgress");
        var completedTask = DataService.GetKitchenTicketsAsync(ShopId, "Completed");
        await Task.WhenAll(pendingTask, inProgressTask, completedTask);

        var pending = await pendingTask;
        var inProgress = await inProgressTask;
        var completed = await completedTask;

        var allTickets = new List<KitchenTicket>();

        // EN: Map API tickets to UI model, group by SessionId for multi-item tickets
        // VI: Ánh xạ phiếu API sang model UI, nhóm theo SessionId cho phiếu nhiều món
        foreach (var group in pending.GroupBy(t => t.SessionId))
        {
            var first = group.First();
            var minutes = (int)(DateTime.UtcNow - first.CreatedAt).TotalMinutes;
            var tableName = _tableLookup.GetValueOrDefault(first.SessionId, $"#{first.SessionId.ToString()[..6]}");
            allTickets.Add(new KitchenTicket(
                first.Id, tableName, "new", Math.Max(0, minutes),
                group.Select(t => new TicketItem(1, t.ItemName, "")).ToList()));
        }

        foreach (var group in inProgress.GroupBy(t => t.SessionId))
        {
            var first = group.First();
            var minutes = (int)(DateTime.UtcNow - first.CreatedAt).TotalMinutes;
            var tableName = _tableLookup.GetValueOrDefault(first.SessionId, $"#{first.SessionId.ToString()[..6]}");
            allTickets.Add(new KitchenTicket(
                first.Id, tableName, "cooking", Math.Max(0, minutes),
                group.Select(t => new TicketItem(1, t.ItemName, "")).ToList()));
        }

        foreach (var group in completed.GroupBy(t => t.SessionId))
        {
            var first = group.First();
            var minutes = (int)(DateTime.UtcNow - first.CreatedAt).TotalMinutes;
            var tableName = _tableLookup.GetValueOrDefault(first.SessionId, $"#{first.SessionId.ToString()[..6]}");
            allTickets.Add(new KitchenTicket(
                first.Id, tableName, "ready", Math.Max(0, minutes),
                group.Select(t => new TicketItem(1, t.ItemName, "")).ToList()));
        }

        _tickets = allTickets;
    }

    // EN: Update ticket status via API / VI: Cập nhật trạng thái phiếu qua API
    private async Task UpdateStatus(KitchenTicket ticket, string newStatus)
    {
        try
        {
            var apiStatus = newStatus switch
            {
                "cooking" => "InProgress",
                "ready" => "Completed",
                "served" => "Completed",
                _ => newStatus
            };
            var success = await DataService.UpdateTicketStatusAsync(ticket.Id,
                new WebClientTpos.Client.Services.PosDataService.UpdateTicketStatusRequest(apiStatus));
            if (success)
            {
                // EN: Reload tickets after status change / VI: Tải lại phiếu sau khi đổi trạng thái
                await LoadTicketsAsync();
            }
        }
        catch { /* silently ignore — next refresh will correct */ }
    }

    private static string ColumnBg(string s) => s switch
    {
        "new" => "rgba(239,68,68,.15)", "cooking" => "rgba(245,158,11,.15)",
        "ready" => "rgba(34,197,94,.15)", _ => "var(--pos-bg-interactive)"
    };

    private static string ColumnColor(string s) => s switch
    {
        "new" => "var(--pos-danger)", "cooking" => "var(--pos-warning)",
        "ready" => "var(--pos-success)", _ => "var(--pos-text-tertiary)"
    };

    private static string TimerBg(int mins) => mins > 15 ? "rgba(239,68,68,.2)" : mins > 10 ? "rgba(245,158,11,.2)" : "rgba(34,197,94,.2)";
    private static string TimerColor(int mins) => mins > 15 ? "var(--pos-danger)" : mins > 10 ? "var(--pos-warning)" : "var(--pos-success)";

    private class KitchenTicket(Guid id, string table, string status, int minutes, List<TicketItem> items)
    {
        public Guid Id { get; set; } = id;
        public string Table { get; set; } = table;
        public string Status { get; set; } = status;
        public int Minutes { get; set; } = minutes;
        public List<TicketItem> Items { get; set; } = items;
    }

    private record TicketItem(int Qty, string Name, string Note);

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