@*
    EN: Karaoke Journey — End-to-end session workflow tracker with 6 steps from reception to payment.
        Loads real room and order data, auto-detects current step based on room status.
    VI: Hanh trinh Karaoke — Theo doi quy trinh phien tu don khach den thanh toan qua 6 buoc.
        Tai du lieu phong va don hang that, tu dong phat hien buoc hien tai theo trang thai phong.
*@
@page "/pos/{ShopId:guid}/karaoke/karaoke-journey"
@page "/pos/{ShopId:guid}/karaoke/karaoke-journey/{RoomId:guid}"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.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("karaoke"))">
            <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
        </button>
        <span style="font-size:16px;font-weight:700;">Hanh trinh Karaoke</span>
        <span style="font-size:12px;color:var(--pos-text-tertiary);">Buoc @(_activeStep + 1)/6</span>
        @if (_room != null)
        {
            <span style="font-size:12px;color:var(--pos-orange-primary);margin-left:auto;font-weight:600;">@_room.TableNumber</span>
        }
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Dang tai...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Khong the tai du lieu phong
        </div>
    }
    else
    {
    @* === STEP INDICATOR / CHI BAO BUOC === *@
    <div style="display:flex;align-items:center;padding:16px;gap:4px;flex-shrink:0;overflow-x:auto;">
        @for (var i = 0; i < _steps.Length; i++)
        {
            var idx = i;
            <div @onclick="() => _activeStep = idx"
                 style="flex:1;display:flex;flex-direction:column;align-items:center;gap:6px;cursor:pointer;min-width:90px;">
                <div style="width:40px;height:40px;border-radius:50%;display:flex;align-items:center;justify-content:center;
                            background:@(idx == _activeStep ? "var(--pos-orange-primary)" : idx < _activeStep ? "rgba(34,197,94,.15)" : "var(--pos-bg-interactive)");
                            color:@(idx == _activeStep ? "#FFF" : idx < _activeStep ? "#22C55E" : "var(--pos-text-tertiary)");
                            transition:all .2s ease;">
                    <i data-lucide="@_steps[idx].Icon" style="width:18px;height:18px;"></i>
                </div>
                <span style="font-size:11px;font-weight:@(idx == _activeStep ? "700" : "500");text-align:center;
                             color:@(idx == _activeStep ? "var(--pos-orange-primary)" : idx < _activeStep ? "#22C55E" : "var(--pos-text-tertiary)");">
                    @_steps[idx].Label
                </span>
            </div>
            @if (i < _steps.Length - 1)
            {
                <div style="flex:0 0 20px;height:2px;background:@(i < _activeStep ? "#22C55E" : "var(--pos-border-subtle)");
                            margin-top:-18px;"></div>
            }
        }
    </div>

    @* === STEP CONTENT / NOI DUNG BUOC === *@
    <div style="flex:1;overflow-y:auto;padding:16px;">
        @switch (_activeStep)
        {
            @* EN: Step 1 -- Guest reception / VI: Buoc 1 -- Don khach *@
            case 0:
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;margin-bottom:16px;">
                    <div style="font-size:14px;font-weight:600;margin-bottom:12px;">
                        <i data-lucide="users" style="width:16px;height:16px;display:inline;"></i> Don khach
                    </div>
                    <div style="display:flex;gap:16px;margin-bottom:16px;">
                        <div style="flex:1;">
                            <div style="font-size:12px;color:var(--pos-text-tertiary);margin-bottom:6px;">So khach</div>
                            <div style="display:flex;align-items:center;gap:12px;">
                                <button style="width:36px;height:36px;border-radius:8px;border:1px solid var(--pos-border-default);
                                               background:transparent;color:var(--pos-text-primary);cursor:pointer;font-size:16px;"
                                        @onclick="() => _guestCount = Math.Max(1, _guestCount - 1)">-</button>
                                <span style="font-size:24px;font-weight:700;min-width:30px;text-align:center;">@_guestCount</span>
                                <button style="width:36px;height:36px;border-radius:8px;border:1px solid var(--pos-border-default);
                                               background:transparent;color:var(--pos-text-primary);cursor:pointer;font-size:16px;"
                                        @onclick="() => _guestCount++">+</button>
                            </div>
                        </div>
                        <div style="flex:1;">
                            <div style="font-size:12px;color:var(--pos-text-tertiary);margin-bottom:6px;">The thanh vien</div>
                            <div style="display:flex;gap:8px;">
                                <div style="flex:1;display:flex;align-items:center;gap:8px;background:var(--pos-bg-interactive);
                                            border-radius:8px;padding:0 12px;border:1px solid var(--pos-border-default);">
                                    <i data-lucide="search" style="width:14px;height:14px;color:var(--pos-text-tertiary);"></i>
                                    <input type="text" placeholder="SDT hoac ma the..." @bind="_memberSearch"
                                           style="flex:1;background:transparent;border:none;color:var(--pos-text-primary);
                                                  font-size:13px;padding:10px 0;outline:none;" />
                                </div>
                            </div>
                            @if (!string.IsNullOrEmpty(_memberSearch))
                            {
                                <div style="font-size:12px;color:#22C55E;margin-top:6px;">
                                    <i data-lucide="check-circle" style="width:12px;height:12px;display:inline;"></i>
                                    Tim kiem thanh vien...
                                </div>
                            }
                        </div>
                    </div>
                    @if (_room != null)
                    {
                        <div style="font-size:12px;color:var(--pos-text-tertiary);padding:8px 12px;background:var(--pos-bg-interactive);border-radius:8px;">
                            Phong da chon: <b>@_room.TableNumber</b> — Suc chua: @_room.Capacity nguoi
                            @if (_room.GuestCount.HasValue && _room.GuestCount > 0)
                            {
                                <span> — Hien tai: @_room.GuestCount khach</span>
                            }
                        </div>
                    }
                </div>
                break;

            @* EN: Step 2 -- Room selection / VI: Buoc 2 -- Chon phong *@
            case 1:
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;margin-bottom:16px;">
                    <div style="font-size:14px;font-weight:600;margin-bottom:12px;">
                        <i data-lucide="door-open" style="width:16px;height:16px;display:inline;"></i> Chon phong
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;">
                        <div style="text-align:center;padding:16px;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);">
                            <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">Phong</div>
                            <div style="font-size:18px;font-weight:700;">@(_room?.TableNumber ?? "---")</div>
                        </div>
                        <div style="text-align:center;padding:16px;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);">
                            <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">Suc chua</div>
                            <div style="font-size:18px;font-weight:700;">@(_room?.Capacity ?? 0) nguoi</div>
                        </div>
                        <div style="text-align:center;padding:16px;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);">
                            <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">Loai</div>
                            <div style="font-size:18px;font-weight:700;">@(_room?.Zone ?? "Standard")</div>
                        </div>
                    </div>
                    <div style="font-size:13px;color:var(--pos-text-secondary);margin-top:12px;text-align:center;">
                        @(_room?.Zone ?? "Khu") • @FormatPrice(_room?.HourlyRate ?? 0)/gio
                    </div>
                </div>
                break;

            @* EN: Step 3 -- Open room / VI: Buoc 3 -- Mo phong *@
            case 2:
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;margin-bottom:16px;">
                    <div style="font-size:14px;font-weight:600;margin-bottom:12px;">
                        <i data-lucide="play" style="width:16px;height:16px;display:inline;"></i> Mo phong
                    </div>
                    <div style="display:flex;flex-direction:column;gap:10px;">
                        <div style="display:flex;justify-content:space-between;font-size:13px;">
                            <span style="color:var(--pos-text-secondary);">Gio bat dau</span>
                            <span style="font-weight:600;">@(_sessionStart?.ToString("HH:mm") ?? DateTime.Now.ToString("HH:mm"))</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;">
                            <span style="color:var(--pos-text-secondary);">Thoi luong du kien</span>
                            <span style="font-weight:600;">@_estimatedHours gio</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;">
                            <span style="color:var(--pos-text-secondary);">Gia/gio</span>
                            <span style="font-weight:600;">@FormatPrice(_hourlyRate)</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;">
                            <span style="color:var(--pos-text-secondary);">Gio ket thuc du kien</span>
                            <span style="font-weight:600;">@((_sessionStart ?? DateTime.Now).AddHours(_estimatedHours).ToString("HH:mm"))</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:14px;font-weight:600;
                                    padding-top:10px;border-top:1px solid var(--pos-border-subtle);">
                            <span>Tam tinh phong</span>
                            <span style="color:var(--pos-orange-primary);">@FormatPrice(_hourlyRate * _estimatedHours)</span>
                        </div>
                    </div>
                </div>
                break;

            @* EN: Step 4 -- In room / VI: Buoc 4 -- Trong phong *@
            case 3:
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:24px;
                            text-align:center;margin-bottom:16px;">
                    <div style="font-size:12px;color:var(--pos-text-tertiary);font-weight:600;margin-bottom:8px;">
                        THOI GIAN SU DUNG
                    </div>
                    <div style="font-size:48px;font-weight:700;color:var(--pos-orange-primary);font-variant-numeric:tabular-nums;">
                        @_sessionElapsed.ToString(@"hh\:mm\:ss")
                    </div>
                    <div style="font-size:13px;color:var(--pos-text-secondary);margin-top:8px;">
                        Bat dau: <b>@(_sessionStart?.ToString("HH:mm") ?? "--:--")</b> •
                        Du kien: <b>@((_sessionStart ?? DateTime.Now).AddHours(_estimatedHours).ToString("HH:mm"))</b>
                    </div>
                </div>
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;margin-bottom:16px;">
                    <div style="font-size:13px;font-weight:600;margin-bottom:10px;">Don F&B hien tai</div>
                    <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:6px;">
                        <span style="color:var(--pos-text-secondary);">So mon</span>
                        <span>@_fnbItemCount mon</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;font-size:14px;font-weight:600;
                                padding-top:8px;border-top:1px solid var(--pos-border-subtle);">
                        <span>Tong F&B</span>
                        <span style="color:var(--pos-orange-primary);">@FormatPrice(_fnbTotal)</span>
                    </div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <button style="padding:14px;border-radius:var(--pos-radius);background:rgba(59,130,246,.15);
                                   border:none;color:#3B82F6;cursor:pointer;font-size:13px;font-weight:500;"
                            @onclick="@(() => NavigateTo($"karaoke/fnb-order/{RoomId}"))">
                        <i data-lucide="utensils" style="width:16px;height:16px;display:block;margin:0 auto 4px;"></i>
                        Goi them F&B
                    </button>
                    <button style="padding:14px;border-radius:var(--pos-radius);background:rgba(255,92,0,.15);
                                   border:none;color:var(--pos-orange-primary);cursor:pointer;font-size:13px;font-weight:500;">
                        <i data-lucide="clock" style="width:16px;height:16px;display:block;margin:0 auto 4px;"></i>
                        Gia han
                    </button>
                </div>
                break;

            @* EN: Step 5 -- Close room / VI: Buoc 5 -- Dong phong *@
            case 4:
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;margin-bottom:16px;">
                    <div style="font-size:14px;font-weight:600;margin-bottom:12px;">
                        <i data-lucide="lock" style="width:16px;height:16px;display:inline;"></i> Ket thuc phien
                    </div>
                    <div style="display:flex;flex-direction:column;gap:8px;">
                        <div style="display:flex;justify-content:space-between;font-size:13px;">
                            <span style="color:var(--pos-text-secondary);">Thoi gian su dung</span>
                            <span style="font-weight:600;">@FormatDuration(_sessionElapsed)</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;">
                            <span style="color:var(--pos-text-secondary);">Tien phong</span>
                            <span>@FormatPrice(RoomCost)</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;">
                            <span style="color:var(--pos-text-secondary);">Tien F&B</span>
                            <span>@FormatPrice(_fnbTotal)</span>
                        </div>
                        <div style="display:flex;justify-content:space-between;font-size:15px;font-weight:700;
                                    padding-top:10px;border-top:1px solid var(--pos-border-subtle);">
                            <span>Tong cong</span>
                            <span style="color:var(--pos-orange-primary);">@FormatPrice(RoomCost + _fnbTotal)</span>
                        </div>
                    </div>
                </div>
                break;

            @* EN: Step 6 -- Payment / VI: Buoc 6 -- Thanh toan *@
            case 5:
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:24px;
                            text-align:center;margin-bottom:16px;">
                    <div style="font-size:12px;color:var(--pos-text-tertiary);font-weight:600;margin-bottom:8px;
                                text-transform:uppercase;letter-spacing:1px;">
                        TONG THANH TOAN
                    </div>
                    <div style="font-size:40px;font-weight:700;color:var(--pos-orange-primary);">
                        @FormatPrice(RoomCost + _fnbTotal)
                    </div>
                    <div style="font-size:13px;color:var(--pos-text-secondary);margin-top:8px;">
                        Phong @(_room?.TableNumber ?? "---") • @FormatDuration(_sessionElapsed) • @_fnbItemCount mon F&B
                    </div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:16px;">
                    <button style="padding:16px;border-radius:var(--pos-radius);background:rgba(34,197,94,.15);
                                   border:none;color:#22C55E;cursor:pointer;font-size:14px;font-weight:600;"
                            @onclick="HandlePayment">
                        <i data-lucide="banknote" style="width:18px;height:18px;display:block;margin:0 auto 4px;"></i>
                        Tien mat
                    </button>
                    <button style="padding:16px;border-radius:var(--pos-radius);background:rgba(59,130,246,.15);
                                   border:none;color:#3B82F6;cursor:pointer;font-size:14px;font-weight:600;"
                            @onclick="HandlePayment">
                        <i data-lucide="credit-card" style="width:18px;height:18px;display:block;margin:0 auto 4px;"></i>
                        The/Chuyen khoan
                    </button>
                </div>
                break;
        }
    </div>

    @* === NAVIGATION BUTTONS / NUT DIEU HUONG === *@
    <div style="display:flex;gap:12px;padding:12px 16px;border-top:1px solid var(--pos-border-subtle);flex-shrink:0;">
        <button style="flex:1;padding:14px;border-radius:var(--pos-radius);background:var(--pos-bg-interactive);
                       border:none;color:var(--pos-text-primary);cursor:pointer;font-size:14px;font-weight:600;
                       opacity:@(_activeStep == 0 ? "0.4" : "1");"
                disabled="@(_activeStep == 0)"
                @onclick="() => _activeStep = Math.Max(0, _activeStep - 1)">
            <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i> Quay lai
        </button>
        <button style="flex:1;padding:14px;border-radius:var(--pos-radius);
                       background:@(_activeStep == _steps.Length - 1 ? "var(--pos-success)" : "var(--pos-orange-primary)");
                       border:none;color:#FFF;cursor:pointer;font-size:14px;font-weight:600;"
                @onclick="HandleNextStep">
            @(_activeStep == _steps.Length - 1 ? "Hoan tat" : "Tiep")
            <i data-lucide="arrow-right" style="width:16px;height:16px;display:inline;"></i>
        </button>
    </div>
    }
</div>

@code {
    // EN: Room ID from route parameter / VI: ID phong tu route parameter
    [Parameter] public Guid RoomId { get; set; }

    // EN: Loading state / VI: Trang thai tai
    private bool _isLoading = true;
    private bool _loadError;

    // EN: Active step index / VI: Chi so buoc hien tai
    private int _activeStep;
    private int _guestCount = 2;
    private string _memberSearch = "";
    private int _estimatedHours = 2;

    // EN: Room data from API / VI: Du lieu phong tu API
    private WebClientTpos.Client.Services.PosDataService.TableInfo? _room;
    private DateTime? _sessionStart;
    private decimal _hourlyRate;

    // EN: F&B order data / VI: Du lieu don F&B
    private decimal _fnbTotal;
    private int _fnbItemCount;

    // EN: Session timer / VI: Dong ho phien
    private TimeSpan _sessionElapsed = TimeSpan.Zero;
    private Timer? _sessionTimer;

    // EN: Room cost based on elapsed time / VI: Chi phi phong theo thoi gian su dung
    private decimal RoomCost
    {
        get
        {
            if (_hourlyRate <= 0) return 0;
            var hours = (decimal)Math.Ceiling(_sessionElapsed.TotalHours);
            if (hours < 1) hours = 1;
            return _hourlyRate * hours;
        }
    }

    // EN: Journey steps / VI: Cac buoc hanh trinh
    private readonly StepInfo[] _steps =
    {
        new("Don khach", "users"),
        new("Chon phong", "door-open"),
        new("Mo phong", "play"),
        new("Trong phong", "music"),
        new("Dong phong", "lock"),
        new("Thanh toan", "credit-card"),
    };

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

        try
        {
            var tables = await DataService.GetTablesAsync(ShopId);

            // EN: Find room by RoomId, or use first room if no RoomId provided
            // VI: Tim phong theo RoomId, hoac dung phong dau tien neu khong co RoomId
            if (RoomId != Guid.Empty)
            {
                _room = tables.FirstOrDefault(t => t.Id == RoomId);
            }
            _room ??= tables.FirstOrDefault();

            if (_room == null)
            {
                _loadError = true;
                return;
            }

            _hourlyRate = _room.HourlyRate > 0 ? _room.HourlyRate : 100_000;
            _guestCount = _room.GuestCount ?? 2;
            _sessionStart = _room.StartedAt;

            // EN: Load F&B orders for this room / VI: Tai don F&B cho phong nay
            var orders = await DataService.GetActiveTableOrdersAsync(ShopId);
            var roomOrders = orders.Where(o => o.TableId == _room.Id).ToList();
            _fnbTotal = roomOrders.Sum(o => o.TotalAmount);
            _fnbItemCount = roomOrders.Sum(o => o.Items.Count);

            // EN: Auto-detect step based on room status / VI: Tu dong phat hien buoc theo trang thai phong
            _activeStep = _room.Status switch
            {
                "occupied" => 3,   // In room
                "cleaning" => 4,   // Close room
                "reserved" => 1,   // Room selection
                _ => 0             // Reception (available)
            };

            // EN: Start session timer if room is occupied / VI: Bat dong ho neu phong dang su dung
            if (_sessionStart.HasValue && _room.Status == "occupied")
            {
                _sessionElapsed = DateTime.Now - _sessionStart.Value;
                _sessionTimer = new Timer(_ =>
                {
                    _sessionElapsed = DateTime.Now - _sessionStart!.Value;
                    InvokeAsync(StateHasChanged);
                }, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
            }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void HandleNextStep()
    {
        if (_activeStep == _steps.Length - 1)
        {
            // EN: Final step - complete / VI: Buoc cuoi - hoan tat
            NavigateTo("karaoke");
        }
        else
        {
            _activeStep = Math.Min(_steps.Length - 1, _activeStep + 1);
        }
    }

    private void HandlePayment()
    {
        // EN: Navigate to payment flow / VI: Dieu huong den thanh toan
        if (_room?.SessionId.HasValue == true)
        {
            NavigateTo($"karaoke/payment/{_room.SessionId}");
        }
        else
        {
            NavigateTo("karaoke");
        }
    }

    private static string FormatDuration(TimeSpan ts)
    {
        if (ts.TotalHours >= 1)
            return $"{(int)ts.TotalHours} gio {ts.Minutes} phut";
        return $"{ts.Minutes} phut";
    }

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

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