@page "/staff/kitchen"
@layout StaffLayout
@implements IDisposable
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject NavigationManager Nav
@inject IJSRuntime JS

@*
    EN: Kitchen display — shows incoming orders/tickets for kitchen staff.
    VI: Màn hình bếp — hiển thị order/phiếu bếp cho nhân viên bếp.
*@

<PageTitle>Bếp - Kitchen Display</PageTitle>

<div class="staff-page">
    <div class="staff-page-header" style="display:flex;align-items:center;justify-content:space-between;">
        <div>
            <h1 class="staff-page-title">Kitchen Display</h1>
            <p class="staff-page-subtitle">Phiếu bếp đang chờ xử lý</p>
        </div>
        <button class="staff-btn-secondary" @onclick="Refresh">
            <i data-lucide="refresh-cw"></i>
            Làm mới
        </button>
    </div>

    @* ═══ STATUS SUMMARY ═══ *@
    <div class="staff-stats-grid" style="margin-bottom:20px;">
        <div class="staff-stat-card">
            <div class="staff-stat-card__icon" style="background:rgba(239,68,68,0.12);">
                <i data-lucide="clock" style="color:#EF4444;"></i>
            </div>
            <span class="staff-stat-card__value">@_pendingCount</span>
            <span class="staff-stat-card__label">Chờ làm</span>
        </div>
        <div class="staff-stat-card">
            <div class="staff-stat-card__icon" style="background:rgba(245,158,11,0.12);">
                <i data-lucide="chef-hat" style="color:#F59E0B;"></i>
            </div>
            <span class="staff-stat-card__value">@_inProgressCount</span>
            <span class="staff-stat-card__label">Đang làm</span>
        </div>
        <div class="staff-stat-card">
            <div class="staff-stat-card__icon" style="background:rgba(34,197,94,0.12);">
                <i data-lucide="check-circle" style="color:#22C55E;"></i>
            </div>
            <span class="staff-stat-card__value">@_completedCount</span>
            <span class="staff-stat-card__label">Hoàn thành</span>
        </div>
    </div>

    @* ═══ TICKET GRID ═══ *@
    @if (_loading)
    {
        <div style="text-align:center;padding:48px;">
            <MudProgressCircular Indeterminate="true" Size="Size.Medium" Color="Color.Success" />
        </div>
    }
    else if (_tickets.Count == 0)
    {
        <div style="text-align:center;padding:48px;">
            <div style="width:64px;height:64px;border-radius:20px;background:rgba(34,197,94,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
                <i data-lucide="check-circle-2" style="width:28px;height:28px;color:#22C55E;"></i>
            </div>
            <h3 style="font-size:16px;font-weight:600;color:var(--admin-text-primary);margin:0 0 8px;">Không có phiếu bếp</h3>
            <p style="font-size:13px;color:var(--admin-text-tertiary);">Tất cả đã được xử lý!</p>
        </div>
    }
    else
    {
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;">
            @foreach (var ticket in _tickets)
            {
                var borderColor = ticket.Status switch
                {
                    "Pending" => "#EF4444",
                    "InProgress" => "#F59E0B",
                    "Ready" => "#22C55E",
                    _ => "var(--admin-border-default)"
                };
                <div style="background:var(--admin-bg-elevated);border:2px solid @borderColor;border-radius:var(--admin-radius-lg);padding:16px;display:flex;flex-direction:column;gap:12px;">
                    <div style="display:flex;align-items:center;justify-content:space-between;">
                        <span style="font-size:16px;font-weight:700;color:var(--admin-text-primary);">#@ticket.OrderNumber</span>
                        <span class="staff-status @GetTicketStatusCss(ticket.Status)">@GetTicketStatusLabel(ticket.Status)</span>
                    </div>
                    <div style="font-size:13px;color:var(--admin-text-tertiary);">@ticket.TableInfo</div>
                    <div style="display:flex;flex-direction:column;gap:6px;">
                        @foreach (var item in ticket.Items)
                        {
                            <div style="display:flex;align-items:center;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--admin-border-subtle);">
                                <span style="font-size:14px;color:var(--admin-text-primary);">@item.Name</span>
                                <span style="font-size:14px;font-weight:600;color:var(--admin-orange-primary);">x@(item.Qty)</span>
                            </div>
                        }
                    </div>
                    <div style="display:flex;gap:8px;margin-top:auto;">
                        @if (ticket.Status == "Pending")
                        {
                            <button class="staff-btn-primary" style="flex:1;justify-content:center;background:#F59E0B;" @onclick="@(() => StartTicket(ticket))">
                                Bắt đầu làm
                            </button>
                        }
                        else if (ticket.Status == "InProgress")
                        {
                            <button class="staff-btn-primary" style="flex:1;justify-content:center;" @onclick="@(() => CompleteTicket(ticket))">
                                Hoàn thành
                            </button>
                        }
                    </div>
                </div>
            }
        </div>
    }
</div>

@code {
    private List<KitchenTicket> _tickets = new();
    private bool _loading = true;
    private int _pendingCount = 0;
    private int _inProgressCount = 0;
    private int _completedCount = 0;
    private System.Threading.Timer? _autoRefreshTimer;

    protected override void OnInitialized()
    {
        // EN: Auto-refresh every 10 seconds for real-time kitchen updates
        // VI: Tự động làm mới mỗi 10 giây cho cập nhật bếp thời gian thực
        _autoRefreshTimer = new System.Threading.Timer(async _ =>
        {
            await InvokeAsync(async () => { await LoadTickets(); StateHasChanged(); });
        }, null, Timeout.Infinite, Timeout.Infinite);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        try { await JS.InvokeVoidAsync("lucide.createIcons"); } catch { }
        if (firstRender)
        {
            await LoadTickets();
            _autoRefreshTimer?.Change(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
            StateHasChanged();
        }
    }

    private async Task LoadTickets()
    {
        _loading = true;
        try
        {
            var apiTickets = await DataService.GetKitchenTicketsAsync(status: null);
            _tickets = apiTickets.Select(t => new KitchenTicket(
                t.Id,
                $"#{t.OrderItemId.ToString()[..6]}",
                t.Station ?? "Kitchen",
                t.Status,
                new List<TicketItem> { new(t.ItemName ?? "Món", 1) }
            )).ToList();
        }
        catch
        {
            // EN: Fallback to empty if API unavailable
            // VI: Để trống nếu API không khả dụng
            _tickets = new();
        }
        _pendingCount = _tickets.Count(t => t.Status == "Pending");
        _inProgressCount = _tickets.Count(t => t.Status == "InProgress");
        _completedCount = _tickets.Count(t => t.Status == "Ready");
        _loading = false;
    }

    private async Task Refresh() => await LoadTickets();

    private async Task StartTicket(KitchenTicket ticket)
    {
        var ok = await DataService.UpdateTicketStatusAsync(ticket.Id, new PosDataService.UpdateTicketStatusRequest("InProgress"));
        if (ok) ticket.Status = "InProgress";
        _pendingCount = _tickets.Count(t => t.Status == "Pending");
        _inProgressCount = _tickets.Count(t => t.Status == "InProgress");
    }

    private async Task CompleteTicket(KitchenTicket ticket)
    {
        var ok = await DataService.UpdateTicketStatusAsync(ticket.Id, new PosDataService.UpdateTicketStatusRequest("Ready"));
        if (ok) ticket.Status = "Ready";
        _inProgressCount = _tickets.Count(t => t.Status == "InProgress");
        _completedCount = _tickets.Count(t => t.Status == "Ready");
    }

    private static string GetTicketStatusCss(string s) => s switch
    {
        "Pending" => "staff-status--danger",
        "InProgress" => "staff-status--warning",
        "Ready" => "staff-status--success",
        _ => "staff-status--neutral"
    };

    private static string GetTicketStatusLabel(string s) => s switch
    {
        "Pending" => "Chờ làm",
        "InProgress" => "Đang làm",
        "Ready" => "Sẵn sàng",
        _ => s
    };

    private class KitchenTicket(Guid id, string orderNumber, string tableInfo, string status, List<TicketItem> items)
    {
        public Guid Id { get; } = id;
        public string OrderNumber { get; } = orderNumber;
        public string TableInfo { get; } = tableInfo;
        public string Status { get; set; } = status;
        public List<TicketItem> Items { get; } = items;
    }

    private record TicketItem(string Name, int Qty);

    public void Dispose() => _autoRefreshTimer?.Dispose();
}
