@*
    EN: Barista Queue — Kanban-style order queue: New / In Progress / Ready columns.
        Connected to kitchen tickets API with auto-refresh every 10 seconds.
    VI: Hàng đợi Barista — Bảng đơn hàng kiểu Kanban: Mới / Đang pha / Sẵn sàng.
        Kết nối API kitchen tickets với auto-refresh mỗi 10 giây.
*@
@page "/pos/{ShopId:guid}/cafe/barista-queue"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@implements IDisposable

<div style="display:flex;gap:16px;padding:16px;height:100%;overflow-x:auto;">
    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;width:100%;color:var(--pos-text-tertiary);">
            Đang tải hàng đợi...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;width:100%;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu. <button style="margin-left:8px;padding:6px 12px;border-radius:8px;border:none;background:var(--pos-orange-primary);color:#fff;cursor:pointer;" @onclick="async () => await LoadTicketsAsync()">Thử lại</button>
        </div>
    }
    else
    {
    @* EN: Kanban columns / VI: Các cột Kanban *@
    @foreach (var column in _columns)
    {
        <div style="flex:1;min-width:280px;display:flex;flex-direction:column;gap:12px;">
            @* EN: Column header / VI: Tiêu đề cột *@
            <div style="display:flex;align-items:center;gap:8px;padding:12px 16px;background:var(--pos-bg-elevated);border-radius:var(--pos-radius);">
                <span style="width:10px;height:10px;border-radius:50%;background:@column.Color;"></span>
                <span style="font-size:15px;font-weight:600;">@column.Title</span>
                <span style="margin-left:auto;font-size:12px;color:var(--pos-text-tertiary);background:var(--pos-bg-interactive);padding:2px 8px;border-radius:6px;">
                    @_tickets.Count(t => t.Status == column.Status)
                </span>
            </div>

            @* EN: Ticket cards / VI: Thẻ ticket *@
            <div style="flex:1;display:flex;flex-direction:column;gap:8px;overflow-y:auto;">
                @foreach (var ticket in _tickets.Where(t => t.Status == column.Status))
                {
                    <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;border-left:3px solid @column.Color;">
                        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                            <span style="font-size:18px;font-weight:700;color:var(--pos-orange-primary);">#@ticket.Id.ToString()[..6].ToUpper()</span>
                            <span style="font-size:11px;color:var(--pos-text-tertiary);">@GetElapsedMinutes(ticket.CreatedAt) phút</span>
                        </div>
                        <div style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:8px;">@(ticket.Station ?? "Barista")</div>
                        <div style="font-size:13px;color:var(--pos-text-primary);padding:2px 0;">@ticket.ItemName</div>
                        @if (ticket.Status != "Completed")
                        {
                            <button style="margin-top:12px;width:100%;padding:8px;border-radius:8px;border:none;background:@column.ActionBg;color:@column.Color;font-size:13px;font-weight:600;cursor:pointer;"
                                    disabled="@ticket.IsUpdating"
                                    @onclick="() => MoveTicket(ticket, column.NextStatus)">
                                @(ticket.IsUpdating ? "Đang cập nhật..." : column.ActionText)
                            </button>
                        }
                        else
                        {
                            <button style="margin-top:12px;width:100%;padding:8px;border-radius:8px;border:none;background:rgba(34,197,94,0.15);color:var(--pos-success);font-size:13px;font-weight:600;cursor:pointer;"
                                    disabled="@ticket.IsUpdating"
                                    @onclick="() => CompleteTicket(ticket)">
                                @(ticket.IsUpdating ? "Đang cập nhật..." : "Đã giao")
                            </button>
                        }
                    </div>
                }
            </div>
        </div>
    }
    }
</div>

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

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

    // EN: Column definitions matching API statuses / VI: Định nghĩa cột khớp status API
    private readonly List<QueueColumn> _columns = new()
    {
        new("Đơn mới", "Pending", "#3B82F6", "Bắt đầu pha", "rgba(59,130,246,0.15)", "InProgress"),
        new("Đang pha", "InProgress", "#F59E0B", "Pha xong", "rgba(245,158,11,0.15)", "Completed"),
        new("Sẵn sàng", "Completed", "#22C55E", "", "", ""),
    };

    // EN: Kitchen tickets loaded from API / VI: Kitchen tickets tải từ API
    private List<TicketViewModel> _tickets = new();

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

        // EN: Start auto-refresh timer / VI: Bắt đầu timer tự động refresh
        _refreshTimer = new Timer(async _ =>
        {
            await InvokeAsync(async () =>
            {
                await LoadTicketsAsync(silent: true);
                StateHasChanged();
            });
        }, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
    }

    private async Task LoadTicketsAsync(bool silent = false)
    {
        if (!silent) { _isLoading = true; _loadError = false; }

        try
        {
            // EN: Fetch all statuses — Pending, InProgress, Completed
            // VI: Lấy tất cả trạng thái — Pending, InProgress, Completed
            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;

            // EN: Merge all tickets, preserve IsUpdating state for existing tickets
            // VI: Gộp tất cả tickets, giữ trạng thái IsUpdating cho ticket đang có
            var allApi = pending.Concat(inProgress).Concat(completed).ToList();
            var existingMap = _tickets.ToDictionary(t => t.Id);

            _tickets = allApi.Select(t =>
            {
                if (existingMap.TryGetValue(t.Id, out var existing) && existing.IsUpdating)
                    return existing;
                return new TicketViewModel(t.Id, t.ItemName, t.Station, t.Status, t.CreatedAt, t.Priority);
            }).ToList();
        }
        catch
        {
            if (!silent) _loadError = true;
        }
        finally
        {
            if (!silent) _isLoading = false;
        }
    }

    private async Task MoveTicket(TicketViewModel ticket, string nextStatus)
    {
        if (string.IsNullOrEmpty(nextStatus) || ticket.IsUpdating) return;
        ticket.IsUpdating = true;
        StateHasChanged();

        try
        {
            var success = await DataService.UpdateTicketStatusAsync(
                ticket.Id, new PosDataService.UpdateTicketStatusRequest(nextStatus));
            if (success)
            {
                ticket.Status = nextStatus;
            }
        }
        catch { /* EN: Silently fail, next refresh will sync / VI: Bỏ qua lỗi, refresh kế tiếp sẽ đồng bộ */ }
        finally
        {
            ticket.IsUpdating = false;
            StateHasChanged();
        }
    }

    private async Task CompleteTicket(TicketViewModel ticket)
    {
        if (ticket.IsUpdating) return;
        ticket.IsUpdating = true;
        StateHasChanged();

        try
        {
            // EN: Mark ticket as delivered — remove from view
            // VI: Đánh dấu ticket đã giao — xóa khỏi danh sách
            var success = await DataService.UpdateTicketStatusAsync(
                ticket.Id, new PosDataService.UpdateTicketStatusRequest("Delivered"));
            if (success)
            {
                _tickets.Remove(ticket);
            }
        }
        catch { }
        finally
        {
            ticket.IsUpdating = false;
            StateHasChanged();
        }
    }

    private static int GetElapsedMinutes(DateTime createdAt)
    {
        return (int)(DateTime.UtcNow - createdAt).TotalMinutes;
    }

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

    // EN: Column definition with next status for transitions / VI: Định nghĩa cột với status kế tiếp cho chuyển đổi
    private record QueueColumn(string Title, string Status, string Color, string ActionText, string ActionBg, string NextStatus);

    // EN: ViewModel wrapping API ticket with UI state / VI: ViewModel bọc API ticket với trạng thái UI
    private class TicketViewModel(Guid id, string itemName, string? station, string status, DateTime createdAt, int priority)
    {
        public Guid Id { get; set; } = id;
        public string ItemName { get; set; } = itemName;
        public string? Station { get; set; } = station;
        public string Status { get; set; } = status;
        public DateTime CreatedAt { get; set; } = createdAt;
        public int Priority { get; set; } = priority;
        public bool IsUpdating { get; set; }
    }
}
