@*
    EN: Cafe Journey — End-to-end cafe workflow tracker: Order -> Payment -> Barista -> Serving -> Complete.
        Connected to order detail & kitchen tickets APIs with auto-refresh every 5 seconds.
    VI: Hanh trinh Cafe — Theo doi quy trinh tu dau den cuoi: Dat mon -> Thanh toan -> Pha che -> Phuc vu -> Hoan tat.
        Ket noi API chi tiet don & kitchen tickets voi auto-refresh moi 5 giay.
*@
@page "/pos/{ShopId:guid}/cafe/cafe-journey/{OrderId:guid}"
@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;">Hanh trinh Cafe</span>
        <span style="flex:1;"></span>
        @if (_orderDetail?.Order != null)
        {
            <span style="font-size:12px;color:var(--pos-text-tertiary);">Don #@(_orderDetail.Order.Id.ToString()[..8].ToUpper())</span>
        }
    </div>

    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Dang tai...
        </div>
    }
    else if (_loadError)
    {
        <div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;color:var(--pos-text-tertiary);">
            <span>Khong the tai du lieu don hang</span>
            <button style="padding:8px 16px;border-radius:8px;border:none;background:var(--pos-orange-primary);color:#fff;cursor:pointer;"
                    @onclick="async () => await LoadDataAsync()">Thu lai</button>
        </div>
    }
    else
    {
    @* ═══ STEP TRACKER / THANH BUOC ═══ *@
    <div style="padding:20px 16px;flex-shrink:0;">
        <div style="display:flex;align-items:center;justify-content:center;gap:0;">
            @for (int i = 0; i < _steps.Count; i++)
            {
                var step = _steps[i];
                var stepIdx = i;
                var isActive = stepIdx == _currentStep;
                var isCompleted = stepIdx < _currentStep;
                var bgColor = isCompleted ? "var(--pos-success)" : isActive ? "var(--pos-orange-primary)" : "var(--pos-bg-interactive)";
                var fgColor = isCompleted || isActive ? "#FFF" : "var(--pos-text-tertiary)";

                @* EN: Step circle / VI: Vong tron buoc *@
                <div style="display:flex;flex-direction:column;align-items:center;z-index:1;">
                    <div style="width:40px;height:40px;border-radius:50%;background:@bgColor;
                                display:flex;align-items:center;justify-content:center;color:@fgColor;
                                font-size:14px;font-weight:700;cursor:pointer;"
                         @onclick="() => _currentStep = stepIdx">
                        @if (isCompleted)
                        {
                            <i data-lucide="check" style="width:18px;height:18px;"></i>
                        }
                        else
                        {
                            <i data-lucide="@step.Icon" style="width:18px;height:18px;"></i>
                        }
                    </div>
                    <div style="font-size:11px;margin-top:6px;font-weight:@(isActive ? "700" : "500");
                                color:@(isActive ? "var(--pos-orange-primary)" : isCompleted ? "var(--pos-success)" : "var(--pos-text-tertiary)");">
                        @step.Label
                    </div>
                </div>

                @* EN: Connector line / VI: Duong noi *@
                @if (stepIdx < _steps.Count - 1)
                {
                    <div style="flex:1;height:2px;max-width:80px;margin:0 8px;margin-bottom:20px;
                                background:@(stepIdx < _currentStep ? "var(--pos-success)" : "var(--pos-border-default)");"></div>
                }
            }
        </div>
    </div>

    @* ═══ STEP CONTENT / NOI DUNG BUOC ═══ *@
    <div style="flex:1;overflow-y:auto;padding:0 16px 16px;">
        @switch (_currentStep)
        {
            case 0:
                @* ═══ DAT MON / ORDER STEP ═══ *@
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;">
                    <div style="font-size:15px;font-weight:700;margin-bottom:16px;">
                        <i data-lucide="clipboard-list" style="width:18px;height:18px;display:inline;"></i> Dat mon
                    </div>
                    <div style="display:flex;flex-direction:column;gap:8px;">
                        @if (_orderItems.Any())
                        {
                            @foreach (var item in _orderItems)
                            {
                                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;
                                            background:var(--pos-bg-interactive);border-radius:8px;">
                                    <div>
                                        <div style="font-size:13px;font-weight:600;">@item.ProductName</div>
                                        <div style="font-size:11px;color:var(--pos-text-tertiary);">x@item.Quantity</div>
                                    </div>
                                    <span style="font-size:14px;font-weight:600;">@FormatPrice(item.UnitPrice * item.Quantity)</span>
                                </div>
                            }
                        }
                        else
                        {
                            <div style="text-align:center;color:var(--pos-text-tertiary);padding:20px;">Khong co mon nao</div>
                        }
                    </div>
                    <div style="display:flex;justify-content:space-between;margin-top:12px;padding-top:12px;
                                border-top:1px solid var(--pos-border-subtle);font-size:15px;font-weight:700;">
                        <span>Tong (@_orderItems.Sum(i => i.Quantity) mon)</span>
                        <span style="color:var(--pos-orange-primary);">@FormatPrice(_orderDetail?.Order?.TotalAmount ?? 0)</span>
                    </div>
                </div>
                break;

            case 1:
                @* ═══ THANH TOAN / PAYMENT STEP ═══ *@
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;">
                    <div style="font-size:15px;font-weight:700;margin-bottom:16px;">
                        <i data-lucide="credit-card" style="width:18px;height:18px;display:inline;"></i> Thanh toan
                    </div>
                    <div style="display:flex;flex-direction:column;gap:10px;">
                        <div style="display:flex;justify-content:space-between;font-size:13px;padding:10px;background:var(--pos-bg-interactive);border-radius:8px;">
                            <span style="color:var(--pos-text-secondary);">Phuong thuc</span>
                            <span style="font-weight:600;">@(_orderDetail?.Order?.PaymentMethod ?? "Chua thanh toan")</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;padding:10px;background:var(--pos-bg-interactive);border-radius:8px;">
                            <span style="color:var(--pos-text-secondary);">Tong tien</span>
                            <span style="font-weight:600;color:var(--pos-orange-primary);">@FormatPrice(_orderDetail?.Order?.TotalAmount ?? 0)</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;padding:10px;background:var(--pos-bg-interactive);border-radius:8px;">
                            <span style="color:var(--pos-text-secondary);">Trang thai</span>
                            <span style="font-weight:600;color:@(_paymentCompleted ? "var(--pos-success)" : "var(--pos-warning)");">
                                @(_paymentCompleted ? "Da thanh toan" : "Chua thanh toan")
                            </span>
                        </div>
                    </div>
                </div>
                break;

            case 2:
                @* ═══ PHA CHE / BARISTA STEP ═══ *@
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;">
                    <div style="font-size:15px;font-weight:700;margin-bottom:16px;">
                        <i data-lucide="coffee" style="width:18px;height:18px;display:inline;"></i> Pha che
                    </div>
                    @if (_orderTickets.Any())
                    {
                        <div style="display:flex;flex-direction:column;gap:10px;">
                            @foreach (var ticket in _orderTickets)
                            {
                                <div style="display:flex;justify-content:space-between;font-size:13px;padding:10px;background:var(--pos-bg-interactive);border-radius:8px;">
                                    <span style="color:var(--pos-text-secondary);">@ticket.ItemName</span>
                                    <span style="font-weight:600;color:@TicketStatusColor(ticket.Status);">@TicketStatusLabel(ticket.Status)</span>
                                </div>
                            }
                        </div>
                        @if (_orderTickets.Any(t => t.Status is "Pending" or "InProgress"))
                        {
                            <div style="margin-top:16px;padding:12px;background:rgba(245,158,11,.1);border-radius:8px;border:1px solid rgba(245,158,11,.3);">
                                <div style="display:flex;align-items:center;gap:8px;">
                                    <span style="width:8px;height:8px;border-radius:50%;background:var(--pos-warning);animation:pulse 1.5s infinite;"></span>
                                    <span style="font-size:12px;color:var(--pos-warning);font-weight:600;">Dang pha @(_orderTickets.Count(t => t.Status is "Pending" or "InProgress")) mon...</span>
                                </div>
                            </div>
                        }
                    }
                    else
                    {
                        <div style="text-align:center;padding:20px;color:var(--pos-text-tertiary);">
                            Chua co kitchen ticket nao cho don nay
                        </div>
                    }
                </div>
                break;

            case 3:
                @* ═══ PHUC VU / SERVING STEP ═══ *@
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;text-align:center;">
                    <div style="font-size:15px;font-weight:700;margin-bottom:16px;">
                        <i data-lucide="bell" style="width:18px;height:18px;display:inline;"></i> Phuc vu
                    </div>
                    <div style="width:100px;height:100px;border-radius:50%;background:@(_allTicketsCompleted ? "rgba(34,197,94,.15)" : "rgba(255,92,0,.15)");
                                display:flex;align-items:center;justify-content:center;margin:20px auto;">
                        @if (_allTicketsCompleted)
                        {
                            <i data-lucide="check-circle" style="width:36px;height:36px;color:var(--pos-success);"></i>
                        }
                        else
                        {
                            <span style="font-size:36px;font-weight:800;color:var(--pos-orange-primary);">
                                #@(_orderDetail?.Order?.Id.ToString()[..4].ToUpper())
                            </span>
                        }
                    </div>
                    <div style="font-size:14px;color:var(--pos-text-secondary);margin-bottom:8px;">
                        @(_allTicketsCompleted ? "San sang phuc vu!" : "Dang cho pha che hoan tat")
                    </div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);">
                        @(_allTicketsCompleted ? "Tat ca mon da hoan thanh" : "Vui long cho goi so tai quay")
                    </div>
                </div>
                break;

            case 4:
                @* ═══ HOAN TAT / COMPLETE STEP ═══ *@
                <div style="text-align:center;padding:40px 20px;">
                    <div style="width:80px;height:80px;border-radius:50%;background:rgba(34,197,94,.15);
                                display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
                        <i data-lucide="check-circle" style="width:40px;height:40px;color:#22C55E;"></i>
                    </div>
                    <div style="font-size:20px;font-weight:700;color:var(--pos-success);margin-bottom:8px;">Hoan tat!</div>
                    <div style="font-size:14px;color:var(--pos-text-secondary);margin-bottom:4px;">
                        Don hang #@(_orderDetail?.Order?.Id.ToString()[..8].ToUpper()) da hoan thanh
                    </div>
                    <div style="font-size:13px;color:var(--pos-text-tertiary);margin-bottom:20px;">
                        @_orderItems.Sum(i => i.Quantity) mon · Tong: @FormatPrice(_orderDetail?.Order?.TotalAmount ?? 0) · @(_orderDetail?.Order?.PaymentMethod ?? "N/A")
                    </div>
                    <div style="display:flex;gap:12px;justify-content:center;">
                        <button style="padding:12px 24px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);
                                       border:1px solid var(--pos-border-default);color:var(--pos-text-primary);cursor:pointer;font-size:13px;">
                            <i data-lucide="printer" style="width:14px;height:14px;display:inline;"></i> In hoa don
                        </button>
                        <button style="padding:12px 24px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);
                                       border:1px solid var(--pos-border-default);color:var(--pos-text-primary);cursor:pointer;font-size:13px;">
                            <i data-lucide="star" style="width:14px;height:14px;display:inline;"></i> Danh gia
                        </button>
                    </div>
                </div>
                break;
        }
    </div>

    @* ═══ FOOTER ACTIONS / NUT HANH DONG ═══ *@
    <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);display:flex;gap:8px;flex-shrink:0;">
        @if (_currentStep > 0)
        {
            <button style="padding:12px 20px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);
                           border:1px solid var(--pos-border-default);color:var(--pos-text-primary);cursor:pointer;font-size:13px;"
                    @onclick="() => _currentStep--">
                <i data-lucide="arrow-left" style="width:14px;height:14px;display:inline;"></i> Quay lai
            </button>
        }
        <span style="flex:1;"></span>
        @if (_currentStep < _steps.Count - 1)
        {
            <button class="pos-btn-checkout" style="width:auto;padding:12px 24px;" @onclick="() => _currentStep++">
                Tiep <i data-lucide="arrow-right" style="width:14px;height:14px;display:inline;"></i>
            </button>
        }
        else
        {
            <button class="pos-btn-checkout" style="width:auto;padding:12px 24px;" @onclick="@(() => NavigateTo("cafe"))">
                <i data-lucide="home" style="width:14px;height:14px;display:inline;"></i> Ve trang chinh
            </button>
        }
    </div>
    }
</div>

@* EN: Pulse animation / VI: Hieu ung nhap nhay *@
<style>
    @@keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.3; }
    }
</style>

@code {
    // EN: Route parameter for order tracking / VI: Tham so route de theo doi don hang
    [Parameter] public Guid OrderId { get; set; }

    // EN: Loading & error states / VI: Trang thai tai & loi
    private bool _isLoading = true;
    private bool _loadError;

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

    private int _currentStep = 0;

    // EN: Journey steps / VI: Cac buoc hanh trinh
    private readonly List<StepInfo> _steps = new()
    {
        new("Dat mon", "clipboard-list"),
        new("Thanh toan", "credit-card"),
        new("Pha che", "coffee"),
        new("Phuc vu", "bell"),
        new("Hoan tat", "check-circle"),
    };

    // EN: Order data from API / VI: Du lieu don hang tu API
    private PosDataService.OrderDetailResponse? _orderDetail;
    private List<PosDataService.OrderItemInfo> _orderItems = new();
    private List<PosDataService.KitchenTicketInfo> _orderTickets = new();

    // EN: Derived states / VI: Trang thai suy ra
    private bool _paymentCompleted => _orderDetail?.Order?.Status is "Paid" or "Completed" or "Validated";
    private bool _allTicketsCompleted => _orderTickets.Any() && _orderTickets.All(t => t.Status == "Completed");

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

        // EN: Start auto-refresh timer / VI: Bat dau timer tu dong refresh
        _refreshTimer = new Timer(async _ =>
        {
            await InvokeAsync(async () =>
            {
                await LoadDataAsync(silent: true);
                AutoAdvanceStep();
                StateHasChanged();
            });
        }, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
    }

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

        try
        {
            // EN: Load order details and kitchen tickets in parallel
            // VI: Tai chi tiet don hang va kitchen tickets song song
            var orderTask = DataService.GetOrderDetailAsync(OrderId, ShopId);
            var pendingTask = DataService.GetKitchenTicketsAsync(ShopId, "Pending");
            var inProgressTask = DataService.GetKitchenTicketsAsync(ShopId, "InProgress");
            var completedTask = DataService.GetKitchenTicketsAsync(ShopId, "Completed");
            await Task.WhenAll(orderTask, pendingTask, inProgressTask, completedTask);

            _orderDetail = await orderTask;
            _orderItems = _orderDetail?.Items ?? new();

            // EN: Filter tickets by order items / VI: Loc tickets theo mon trong don
            var allTickets = (await pendingTask).Concat(await inProgressTask).Concat(await completedTask).ToList();
            var orderItemIds = _orderItems.Select(i => i.Id).ToHashSet();
            _orderTickets = allTickets.Where(t => orderItemIds.Contains(t.OrderItemId)).ToList();

            // EN: If no tickets matched by OrderItemId, try matching by item name
            // VI: Neu khong co ticket nao khop theo OrderItemId, thu khop theo ten mon
            if (!_orderTickets.Any() && _orderItems.Any())
            {
                var itemNames = _orderItems.Select(i => i.ProductName).Where(n => n != null).ToHashSet();
                _orderTickets = allTickets.Where(t => itemNames.Contains(t.ItemName)).ToList();
            }

            if (!silent) AutoAdvanceStep();
        }
        catch
        {
            if (!silent) _loadError = true;
        }
        finally
        {
            if (!silent) _isLoading = false;
        }
    }

    // EN: Auto-advance steps based on order/ticket status
    // VI: Tu dong chuyen buoc dua tren trang thai don/ticket
    private void AutoAdvanceStep()
    {
        if (_orderDetail?.Order == null) return;

        // EN: Step 0 (Order) always done if we have items
        // EN: Step 1 (Payment) done if paid
        // EN: Step 2 (Barista) done if all tickets completed
        // EN: Step 3 (Serving) done if all tickets completed and order marked complete
        // EN: Step 4 (Complete) final

        if (_orderDetail.Order.Status is "Completed")
        {
            _currentStep = 4;
        }
        else if (_allTicketsCompleted)
        {
            _currentStep = Math.Max(_currentStep, 3);
        }
        else if (_orderTickets.Any(t => t.Status is "InProgress" or "Completed"))
        {
            _currentStep = Math.Max(_currentStep, 2);
        }
        else if (_paymentCompleted)
        {
            _currentStep = Math.Max(_currentStep, 1);
        }
    }

    private static string TicketStatusColor(string status) => status switch
    {
        "Completed" => "var(--pos-success)",
        "InProgress" => "var(--pos-warning)",
        "Pending" => "var(--pos-info)",
        _ => "var(--pos-text-tertiary)"
    };

    private static string TicketStatusLabel(string status) => status switch
    {
        "Completed" => "Hoan thanh",
        "InProgress" => "Dang pha",
        "Pending" => "Cho",
        _ => status
    };

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

    private record StepInfo(string Label, string Icon);
}
