@*
    EN: Barista Queue Dashboard — Kanban-style drink preparation queue with stats, auto-refresh,
        and barista assignment. Connected to fnb-engine barista queue API.
    VI: Bang Dieu Khien Hang Doi Barista — Hang doi pha che kieu Kanban voi thong ke, tu dong lam moi,
        va phan cong barista. Ket noi API hang doi barista cua fnb-engine.
*@
@page "/pos/{ShopId:guid}/cafe/barista"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@implements IDisposable

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">

    @* ═══ HEADER / TIEU DE ═══ *@
    <div style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);flex-shrink:0;">
        <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("cafe"))">
            <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
        </button>
        <span style="font-size:16px;font-weight:700;">Hang doi Barista</span>
        <span style="flex:1;"></span>
        <span style="font-size:11px;color:var(--pos-text-tertiary);">
            Tu dong cap nhat moi 10 giay
        </span>
    </div>

    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            <div style="text-align:center;">
                <div style="width:40px;height:40px;border:3px solid var(--pos-border-subtle);border-top-color:var(--pos-orange-primary);
                            border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 12px;"></div>
                <div>Dang tai hang doi...</div>
            </div>
        </div>
    }
    else if (_loadError)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Khong the tai du lieu.
            <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 LoadQueueAsync()">Thu lai</button>
        </div>
    }
    else
    {
        @* ═══ STATS BAR / THANH THONG KE ═══ *@
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;padding:12px 16px;flex-shrink:0;">
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px;text-align:center;">
                <div style="font-size:24px;font-weight:700;color:var(--pos-orange-primary);">@_stats.TotalQueued</div>
                <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Cho pha</div>
            </div>
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px;text-align:center;">
                <div style="font-size:24px;font-weight:700;color:#3B82F6;">@_stats.Preparing</div>
                <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Dang pha</div>
            </div>
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px;text-align:center;">
                <div style="font-size:24px;font-weight:700;color:var(--pos-success);">@_stats.Ready</div>
                <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">San sang</div>
            </div>
            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px;text-align:center;">
                <div style="font-size:24px;font-weight:700;color:var(--pos-text-primary);">@_stats.AvgPrepTimeMinutes.ToString("F1")</div>
                <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">TB phut</div>
            </div>
        </div>

        @* ═══ KANBAN COLUMNS / COT KANBAN ═══ *@
        <div style="flex:1;display:flex;gap:16px;padding:0 16px 16px;overflow-x:auto;">
            @foreach (var col in _columns)
            {
                var items = _queueItems.Where(q => q.Status == col.Status).OrderByDescending(q => q.Priority).ThenBy(q => q.CreatedAt).ToList();

                <div style="flex:1;min-width:280px;display:flex;flex-direction:column;gap:10px;">
                    @* EN: Column header / VI: Tieu de cot *@
                    <div style="display:flex;align-items:center;gap:8px;padding:12px 16px;
                                background:@col.HeaderBg;border-radius:var(--pos-radius);">
                        <span style="width:10px;height:10px;border-radius:50%;background:@col.Color;"></span>
                        <span style="font-size:14px;font-weight:700;color:@col.Color;">@col.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;">
                            @items.Count
                        </span>
                    </div>

                    @* EN: Drink cards / VI: The ly *@
                    <div style="flex:1;display:flex;flex-direction:column;gap:8px;overflow-y:auto;">
                        @foreach (var item in items)
                        {
                            <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:14px;
                                        border-left:3px solid @col.Color;
                                        @(col.Status == "Ready" ? "animation:readyPulse 2s ease-in-out infinite;" : "")">

                                @* EN: Drink header / VI: Tieu de ly *@
                                <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:6px;">
                                    <div style="font-size:15px;font-weight:700;color:var(--pos-text-primary);">@item.DrinkName</div>
                                    @if (item.Priority > 0)
                                    {
                                        <span style="font-size:10px;font-weight:700;padding:2px 6px;border-radius:4px;
                                                     background:rgba(239,68,68,0.2);color:var(--pos-danger);">
                                            Uu tien
                                        </span>
                                    }
                                </div>

                                @* EN: Customizations / VI: Tuy chinh *@
                                @if (!string.IsNullOrEmpty(item.Customizations))
                                {
                                    <div style="font-size:12px;color:var(--pos-text-secondary);margin-bottom:6px;
                                                padding:4px 8px;background:var(--pos-bg-interactive);border-radius:6px;">
                                        @item.Customizations
                                    </div>
                                }

                                @* EN: Meta row / VI: Dong thong tin *@
                                <div style="display:flex;justify-content:space-between;align-items:center;font-size:11px;
                                            color:var(--pos-text-tertiary);margin-bottom:10px;">
                                    <span>@GetElapsedMinutes(item.CreatedAt) phut truoc</span>
                                    <span>~@item.EstimatedMinutes phut</span>
                                </div>

                                @* EN: Assigned barista (Preparing column) / VI: Barista duoc phan cong (cot Dang pha) *@
                                @if (!string.IsNullOrEmpty(item.AssignedTo) && col.Status == "Preparing")
                                {
                                    <div style="font-size:12px;color:#3B82F6;margin-bottom:8px;font-weight:600;">
                                        <i data-lucide="user" style="width:12px;height:12px;display:inline;"></i> @item.AssignedTo
                                    </div>
                                }

                                @* EN: Action button / VI: Nut hanh dong *@
                                @if (col.Status == "Queued")
                                {
                                    <button style="width:100%;padding:8px;border-radius:8px;border:none;
                                                   background:rgba(59,130,246,0.15);color:#3B82F6;
                                                   font-size:13px;font-weight:600;cursor:pointer;"
                                            disabled="@_processingIds.Contains(item.Id)"
                                            @onclick="() => ShowBaristaDialog(item)">
                                        @(_processingIds.Contains(item.Id) ? "Dang xu ly..." : "Bat dau pha")
                                    </button>
                                }
                                else if (col.Status == "Preparing")
                                {
                                    <button style="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="@_processingIds.Contains(item.Id)"
                                            @onclick="() => MarkReadyAsync(item)">
                                        @(_processingIds.Contains(item.Id) ? "Dang xu ly..." : "Hoan thanh")
                                    </button>
                                }
                                else if (col.Status == "Ready")
                                {
                                    <button style="width:100%;padding:8px;border-radius:8px;border:none;
                                                   background:rgba(245,158,11,0.15);color:var(--pos-warning);
                                                   font-size:13px;font-weight:600;cursor:pointer;"
                                            disabled="@_processingIds.Contains(item.Id)"
                                            @onclick="() => MarkDeliveredAsync(item)">
                                        @(_processingIds.Contains(item.Id) ? "Dang xu ly..." : "Da giao")
                                    </button>
                                }
                            </div>
                        }
                    </div>
                </div>
            }
        </div>
    }
</div>

@* EN: Barista name dialog overlay / VI: Hop thoai nhap ten barista *@
@if (_showBaristaDialog)
{
    <div style="position:fixed;inset:0;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;z-index:100;"
         @onclick="() => _showBaristaDialog = false">
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:24px;
                    width:320px;max-width:90vw;" @onclick:stopPropagation="true">
            <div style="font-size:15px;font-weight:700;margin-bottom:16px;">Nhap ten Barista</div>
            <input type="text" placeholder="Ten barista..." value="@_baristaName"
                   style="width:100%;padding:12px;border-radius:8px;border:1px solid var(--pos-border-default);
                          background:var(--pos-bg-interactive);color:var(--pos-text-primary);font-size:14px;
                          outline:none;box-sizing:border-box;margin-bottom:16px;"
                   @onchange="@((ChangeEventArgs e) => _baristaName = e.Value?.ToString() ?? "")" />
            <div style="display:flex;gap:8px;">
                <button style="flex:1;padding:10px;border-radius:8px;border:1px solid var(--pos-border-default);
                               background:transparent;color:var(--pos-text-secondary);cursor:pointer;font-size:13px;"
                        @onclick="() => _showBaristaDialog = false">Huy</button>
                <button style="flex:1;padding:10px;border-radius:8px;border:none;
                               background:var(--pos-orange-primary);color:#fff;cursor:pointer;font-size:13px;font-weight:600;"
                        disabled="@string.IsNullOrWhiteSpace(_baristaName)"
                        @onclick="ConfirmStartPreparing">Xac nhan</button>
            </div>
        </div>
    </div>
}

@* EN: CSS animation for ready pulse / VI: CSS animation cho nhap nhay san sang *@
<style>
    @@keyframes readyPulse {
        0%, 100% { box-shadow: 0 0 0 0 rgba(34,197,94,0); }
        50% { box-shadow: 0 0 12px 2px rgba(34,197,94,0.3); }
    }
</style>

@code {
    // EN: Loading / error state / VI: Trang thai tai / loi
    private bool _isLoading = true;
    private bool _loadError;
    private bool _disposed;

    // EN: Auto-refresh timer (10 seconds) / VI: Timer tu dong lam moi (10 giay)
    private Timer? _refreshTimer;

    // EN: Queue data / VI: Du lieu hang doi
    private List<PosDataService.BaristaQueueItemInfo> _queueItems = new();
    private PosDataService.BaristaQueueStatsInfo _stats = new(0, 0, 0, 0);

    // EN: Processing state per item / VI: Trang thai xu ly theo mon
    private readonly HashSet<Guid> _processingIds = new();

    // EN: Barista name dialog state / VI: Trang thai hop thoai ten barista
    private bool _showBaristaDialog;
    private string _baristaName = "";
    private PosDataService.BaristaQueueItemInfo? _selectedItem;

    // EN: Column definitions / VI: Dinh nghia cot
    private static readonly QueueColumnDef[] _columns = new[]
    {
        new QueueColumnDef("Cho pha", "Queued", "#F59E0B", "rgba(245,158,11,0.1)"),
        new QueueColumnDef("Dang pha", "Preparing", "#3B82F6", "rgba(59,130,246,0.1)"),
        new QueueColumnDef("San sang", "Ready", "#22C55E", "rgba(34,197,94,0.1)"),
    };

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

        // EN: Start auto-refresh with _disposed guard / VI: Bat dau tu dong lam moi voi guard _disposed
        _refreshTimer = new Timer(async _ =>
        {
            if (_disposed) return;
            try
            {
                await LoadQueueAsync(silent: true);
                if (!_disposed) await InvokeAsync(StateHasChanged);
            }
            catch { /* EN: Silently ignore refresh errors / VI: Bo qua loi lam moi */ }
        }, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
    }

    /// <summary>
    /// EN: Load queue items and stats from the barista queue API.
    /// VI: Tai danh sach mon va thong ke tu API hang doi barista.
    /// </summary>
    private async Task LoadQueueAsync(bool silent = false)
    {
        if (!silent) { _isLoading = true; _loadError = false; }

        try
        {
            // EN: Load queue items and stats in parallel / VI: Tai mon va thong ke song song
            var itemsTask = DataService.GetBaristaQueueAsync(ShopId);
            var statsTask = DataService.GetBaristaQueueStatsAsync(ShopId);
            await Task.WhenAll(itemsTask, statsTask);

            var newItems = await itemsTask;
            var newStats = await statsTask;

            // EN: Preserve processing state for items being updated
            // VI: Giu trang thai xu ly cho cac mon dang cap nhat
            _queueItems = newItems;
            _stats = newStats ?? new PosDataService.BaristaQueueStatsInfo(
                newItems.Count(q => q.Status == "Queued"),
                newItems.Count(q => q.Status == "Preparing"),
                newItems.Count(q => q.Status == "Ready"),
                0);
        }
        catch
        {
            if (!silent) _loadError = true;
        }
        finally
        {
            if (!silent) _isLoading = false;
        }
    }

    /// <summary>
    /// EN: Show the barista name dialog before starting preparation.
    /// VI: Hien thi hop thoai nhap ten barista truoc khi bat dau pha che.
    /// </summary>
    private void ShowBaristaDialog(PosDataService.BaristaQueueItemInfo item)
    {
        _selectedItem = item;
        _baristaName = "";
        _showBaristaDialog = true;
    }

    /// <summary>
    /// EN: Confirm barista name and start preparing the drink.
    /// VI: Xac nhan ten barista va bat dau pha che ly.
    /// </summary>
    private async Task ConfirmStartPreparing()
    {
        if (_selectedItem == null || string.IsNullOrWhiteSpace(_baristaName)) return;

        _showBaristaDialog = false;
        _processingIds.Add(_selectedItem.Id);
        StateHasChanged();

        try
        {
            var success = await DataService.StartPreparingDrinkAsync(_selectedItem.Id, _baristaName.Trim());
            if (success)
            {
                await LoadQueueAsync(silent: true);
            }
        }
        catch { /* EN: Next refresh will sync / VI: Lan lam moi ke tiep se dong bo */ }
        finally
        {
            _processingIds.Remove(_selectedItem.Id);
            StateHasChanged();
        }
    }

    /// <summary>
    /// EN: Mark a drink as ready for pickup.
    /// VI: Danh dau ly da san sang de lay.
    /// </summary>
    private async Task MarkReadyAsync(PosDataService.BaristaQueueItemInfo item)
    {
        _processingIds.Add(item.Id);
        StateHasChanged();

        try
        {
            var success = await DataService.MarkDrinkReadyAsync(item.Id);
            if (success) await LoadQueueAsync(silent: true);
        }
        catch { }
        finally
        {
            _processingIds.Remove(item.Id);
            StateHasChanged();
        }
    }

    /// <summary>
    /// EN: Mark a drink as delivered and remove from queue.
    /// VI: Danh dau ly da giao va xoa khoi hang doi.
    /// </summary>
    private async Task MarkDeliveredAsync(PosDataService.BaristaQueueItemInfo item)
    {
        _processingIds.Add(item.Id);
        StateHasChanged();

        try
        {
            var success = await DataService.MarkDrinkDeliveredAsync(item.Id);
            if (success) await LoadQueueAsync(silent: true);
        }
        catch { }
        finally
        {
            _processingIds.Remove(item.Id);
            StateHasChanged();
        }
    }

    private static int GetElapsedMinutes(DateTime createdAt)
        => Math.Max(0, (int)(DateTime.UtcNow - createdAt).TotalMinutes);

    public void Dispose()
    {
        _disposed = true;
        _refreshTimer?.Dispose();
    }

    private record QueueColumnDef(string Title, string Status, string Color, string HeaderBg);
}
