@*
    EN: Karaoke Room Extend — Extension dialog with time options, loads room info from DB.
    VI: Gia hạn phòng Karaoke — Dialog gia hạn với tùy chọn thời gian, tải thông tin phòng từ DB.
*@
@page "/pos/{ShopId:guid}/karaoke/room-extend/{RoomId:guid}"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER / TIÊU ĐỀ ═══ *@
    <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/room-session/{RoomId}"))">
            <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
        </button>
        <span style="font-size:16px;font-weight:700;">Gia hạn phòng</span>
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else
    {
    <div style="flex:1;overflow-y:auto;padding:16px;">
        @* ═══ CURRENT SESSION INFO / THÔNG TIN PHIÊN HIỆN TẠI ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;margin-bottom:16px;">
            <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:12px;">
                <div>
                    <div style="font-size:18px;font-weight:700;">@_roomName</div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);">@_roomType • @_roomCapacity người</div>
                </div>
                <span style="font-size:12px;padding:4px 10px;border-radius:6px;font-weight:600;
                             background:rgba(34,197,94,.15);color:#22C55E;">Đang hoạt động</span>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div style="text-align:center;padding:12px;background:var(--pos-bg-interactive);border-radius:8px;">
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">Bắt đầu</div>
                    <div style="font-size:16px;font-weight:700;">@(_sessionStart?.ToLocalTime().ToString("HH:mm") ?? "--:--")</div>
                </div>
                <div style="text-align:center;padding:12px;background:var(--pos-bg-interactive);border-radius:8px;">
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">Đã dùng</div>
                    <div style="font-size:16px;font-weight:700;color:var(--pos-orange-primary);">@_elapsedStr</div>
                </div>
            </div>
        </div>

        @* ═══ EXTENSION OPTIONS / TÙY CHỌN GIA HẠN ═══ *@
        <div style="margin-bottom:16px;">
            <div style="font-size:14px;font-weight:600;margin-bottom:12px;">Chọn thời gian gia hạn</div>
            <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:10px;">
                @foreach (var opt in _extendOptions)
                {
                    <button @onclick="() => _selectedOption = opt"
                            style="padding:20px 12px;border-radius:var(--pos-radius);text-align:center;cursor:pointer;
                                   background:@(_selectedOption?.Minutes == opt.Minutes ? "var(--pos-orange-primary)" : "var(--pos-bg-elevated)");
                                   color:@(_selectedOption?.Minutes == opt.Minutes ? "#FFF" : "var(--pos-text-primary)");
                                   border:1px solid @(_selectedOption?.Minutes == opt.Minutes ? "var(--pos-orange-primary)" : "var(--pos-border-subtle)");">
                        <div style="font-size:16px;font-weight:700;">@opt.Label</div>
                    </button>
                }
            </div>
        </div>

        @* EN: Custom input / VI: Nhập tùy chỉnh *@
        <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:8px;">Tùy chỉnh (phút)</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="() => _customMinutes = Math.Max(15, _customMinutes - 15)">−</button>
                <span style="font-size:20px;font-weight:700;min-width:50px;text-align:center;">@_customMinutes</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="() => _customMinutes += 15">+</button>
                <span style="font-size:13px;color:var(--pos-text-tertiary);">phút</span>
                <button style="padding:8px 14px;border-radius:8px;background:var(--pos-bg-interactive);
                               border:none;color:var(--pos-text-primary);cursor:pointer;font-size:12px;font-weight:600;"
                        @onclick="ApplyCustom">
                    Áp dụng
                </button>
            </div>
        </div>
    </div>

    @* EN: Success/Error message / VI: Thông báo thành công/lỗi *@
    @if (!string.IsNullOrEmpty(_statusMessage))
    {
        <div style="margin:0 16px;padding:10px 14px;border-radius:8px;font-size:13px;font-weight:500;
                    background:@(_isError ? "rgba(239,68,68,.15)" : "rgba(34,197,94,.15)");
                    color:@(_isError ? "#EF4444" : "#22C55E");">
            @_statusMessage
        </div>
    }

    @* ═══ ACTION BUTTONS / NÚT HÀNH ĐỘNG ═══ *@
    <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;"
                @onclick="@(() => NavigateTo($"karaoke/room-session/{RoomId}"))">
            Hủy
        </button>
        <button style="flex:1;padding:14px;border-radius:var(--pos-radius);background:var(--pos-orange-primary);
                       border:none;color:#FFF;cursor:pointer;font-size:14px;font-weight:600;
                       opacity:@(_selectedOption is null || _isExtending ? "0.4" : "1");"
                disabled="@(_selectedOption is null || _isExtending)"
                @onclick="ConfirmExtend">
            @if (_isExtending)
            {
                <text>Đang xử lý...</text>
            }
            else
            {
                <i data-lucide="check" style="width:16px;height:16px;display:inline;"></i> <text>Xác nhận gia hạn</text>
            }
        </button>
    </div>
    }
</div>

@code {
    [Parameter] public Guid RoomId { get; set; }

    private bool _isLoading = true;
    private string _roomName = "";
    private string _roomType = "";
    private int _roomCapacity;
    private DateTime? _sessionStart;
    private string _elapsedStr = "--";

    private readonly List<ExtendOption> _extendOptions = new()
    {
        new(30, "+30 phút"),
        new(60, "+1 giờ"),
        new(90, "+1.5 giờ"),
        new(120, "+2 giờ"),
    };

    private ExtendOption? _selectedOption;
    private int _customMinutes = 45;
    private bool _isExtending;
    private string? _statusMessage;
    private bool _isError;

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

        try
        {
            var tables = await DataService.GetTablesAsync(ShopId);
            var table = tables.FirstOrDefault(t => t.Id == RoomId);
            if (table != null)
            {
                _roomName = table.TableNumber;
                _roomType = table.Zone ?? "Standard";
                _roomCapacity = table.Capacity;
                _sessionStart = table.StartedAt;
                if (_sessionStart.HasValue)
                {
                    var elapsed = DateTime.Now - _sessionStart.Value;
                    _elapsedStr = $"{(int)elapsed.TotalHours}h{elapsed.Minutes:D2}";
                }
            }
        }
        catch { }
        finally
        {
            _isLoading = false;
        }
    }

    private void ApplyCustom()
    {
        _selectedOption = new(_customMinutes, $"+{_customMinutes} phút");
    }

    /// <summary>
    /// EN: Call API to extend the session, then navigate back on success.
    /// VI: Gọi API gia hạn phiên, sau đó quay lại khi thành công.
    /// </summary>
    private async Task ConfirmExtend()
    {
        if (_selectedOption is null || _isExtending) return;

        _isExtending = true;
        _statusMessage = null;
        StateHasChanged();

        try
        {
            var success = await DataService.ExtendSessionAsync(RoomId, _selectedOption.Minutes);
            if (success)
            {
                _statusMessage = $"Gia hạn thành công {_selectedOption.Label}!";
                _isError = false;
                StateHasChanged();
                // EN: Brief delay so user sees success message before navigating
                // VI: Delay ngắn để user thấy thông báo thành công trước khi chuyển trang
                await Task.Delay(800);
                NavigateTo($"karaoke/room-session/{RoomId}");
            }
            else
            {
                _statusMessage = "Không thể gia hạn phiên. Vui lòng thử lại.";
                _isError = true;
            }
        }
        catch (Exception ex)
        {
            _statusMessage = $"Lỗi: {ex.Message}";
            _isError = true;
        }
        finally
        {
            _isExtending = false;
        }
    }

    private record ExtendOption(int Minutes, string Label);
}
