@*
    EN: Karaoke Member Card — Member lookup, tier info, points, history, apply discount.
    VI: Thẻ thành viên Karaoke — Tra cứu thành viên, hạng, điểm, lịch sử, áp dụng giảm giá.
*@
@page "/pos/{ShopId:guid}/karaoke/member-card"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;overflow:hidden;">
    @* ═══ MEMBER LOOKUP (LEFT) / TRA CỨU THÀNH VIÊN (TRÁI) ═══ *@
    <div class="pos-product-panel" style="padding:16px;overflow-y:auto;">
        @* EN: Header / VI: Tiêu đề *@
        <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
            <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;">Thẻ thành viên</span>
        </div>

        @* EN: Search bar / VI: Thanh tìm kiếm *@
        <div style="display:flex;gap:8px;margin-bottom:16px;">
            <div style="flex:1;display:flex;align-items:center;gap:8px;background:var(--pos-bg-elevated);
                        border-radius:var(--pos-radius);padding:0 14px;border:1px solid var(--pos-border-default);">
                <i data-lucide="search" style="width:16px;height:16px;color:var(--pos-text-tertiary);"></i>
                <input type="text" placeholder="SĐT hoặc mã thẻ..." @bind="_searchTerm"
                       @onkeydown="HandleSearchKeyDown"
                       style="flex:1;background:transparent;border:none;color:var(--pos-text-primary);
                              font-size:14px;padding:12px 0;outline:none;" />
            </div>
            <button style="padding:12px 16px;border-radius:var(--pos-radius);background:var(--pos-orange-primary);
                           border:none;color:#FFF;cursor:pointer;font-size:13px;font-weight:600;"
                    disabled="@_isSearching"
                    @onclick="SearchMember">
                @if (_isSearching)
                {
                    <text>...</text>
                }
                else
                {
                    <i data-lucide="search" style="width:16px;height:16px;display:inline;"></i> <text>Tìm</text>
                }
            </button>
        </div>

        @* EN: Search status messages / VI: Thông báo trạng thái tìm kiếm *@
        @if (!string.IsNullOrEmpty(_searchMessage))
        {
            <div style="padding:10px 14px;border-radius:8px;margin-bottom:12px;font-size:13px;
                        background:@(_searchError ? "rgba(239,68,68,.15)" : "rgba(59,130,246,.15)");
                        color:@(_searchError ? "#EF4444" : "#3B82F6");">
                @_searchMessage
            </div>
        }

        @* ═══ MEMBER CARD DISPLAY / HIỂN THỊ THẺ THÀNH VIÊN ═══ *@
        @if (_activeMember is not null)
        {
            <div style="background:linear-gradient(135deg,#1A1A1D,#2A2A2E);border-radius:16px;padding:24px;
                        margin-bottom:16px;border:1px solid rgba(255,92,0,.3);">
                <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:16px;">
                    <div>
                        <div style="font-size:20px;font-weight:700;">@_activeMember.Name</div>
                        <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:2px;">@_activeMember.Phone</div>
                    </div>
                    <span style="padding:4px 12px;border-radius:8px;font-size:12px;font-weight:700;
                                 background:@GetTierBg(_activeMember.Tier);color:@GetTierFg(_activeMember.Tier);">
                        @_activeMember.Tier
                    </span>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;">
                    <div style="text-align:center;padding:12px;background:rgba(255,255,255,.05);border-radius:10px;">
                        <div style="font-size:20px;font-weight:700;color:var(--pos-orange-primary);">@_activeMember.Points</div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Điểm</div>
                    </div>
                    <div style="text-align:center;padding:12px;background:rgba(255,255,255,.05);border-radius:10px;">
                        <div style="font-size:20px;font-weight:700;">@_activeMember.Visits</div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Lượt đến</div>
                    </div>
                    <div style="text-align:center;padding:12px;background:rgba(255,255,255,.05);border-radius:10px;">
                        <div style="font-size:20px;font-weight:700;color:#22C55E;">@_activeMember.Discount%</div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Giảm giá</div>
                    </div>
                </div>
                <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:12px;text-align:center;">
                    Mã thẻ: @_activeMember.CardId • Từ @_activeMember.JoinDate
                </div>
            </div>

            @* ═══ VISIT HISTORY / LỊCH SỬ ĐẾN ═══ *@
            <div style="font-size:14px;font-weight:600;margin-bottom:10px;">Lịch sử gần đây</div>
            @foreach (var visit in _visitHistory)
            {
                <div style="display:flex;align-items:center;gap:12px;padding:12px;
                            background:var(--pos-bg-elevated);border-radius:var(--pos-radius);
                            margin-bottom:8px;border:1px solid var(--pos-border-subtle);">
                    <div style="width:40px;height:40px;border-radius:10px;background:var(--pos-bg-interactive);
                                display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                        <i data-lucide="mic" style="width:18px;height:18px;color:var(--pos-text-tertiary);"></i>
                    </div>
                    <div style="flex:1;">
                        <div style="font-size:13px;font-weight:600;">@visit.Room</div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);">@visit.Date • @visit.Duration</div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:13px;font-weight:600;">@FormatPrice(visit.Total)</div>
                        <div style="font-size:11px;color:#22C55E;">+@visit.Points điểm</div>
                    </div>
                </div>
            }
        }
        else
        {
            <div style="text-align:center;padding:60px 16px;color:var(--pos-text-tertiary);">
                <i data-lucide="credit-card" style="width:48px;height:48px;display:block;margin:0 auto 12px;opacity:.4;"></i>
                <div style="font-size:14px;">Nhập SĐT hoặc quét thẻ để tra cứu</div>
            </div>
        }
    </div>

    @* ═══ DISCOUNT PANEL (RIGHT) / PANEL GIẢM GIÁ (PHẢI) ═══ *@
    <div class="pos-cart-panel">
        @if (_activeMember is not null)
        {
            <div class="pos-cart-header">
                <span class="pos-cart-header__title">Áp dụng ưu đãi</span>
            </div>

            <div class="pos-cart-items" style="padding:12px;">
                @* EN: Available rewards / VI: Ưu đãi khả dụng *@
                @foreach (var reward in _rewards)
                {
                    <div @onclick="() => _selectedReward = reward"
                         style="padding:14px;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);
                                margin-bottom:8px;cursor:pointer;
                                border:2px solid @(_selectedReward?.Id == reward.Id ? "var(--pos-orange-primary)" : "transparent");">
                        <div style="display:flex;justify-content:space-between;align-items:center;">
                            <span style="font-size:13px;font-weight:600;">@reward.Name</span>
                            <span style="font-size:12px;color:var(--pos-orange-primary);font-weight:600;">@reward.Value</span>
                        </div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:4px;">@reward.Description</div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Cần @reward.PointCost điểm</div>
                    </div>
                }
            </div>

            <div class="pos-cart-footer">
                <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:8px;">
                    <span style="color:var(--pos-text-secondary);">Giảm hạng thành viên</span>
                    <span>-@_activeMember.Discount%</span>
                </div>
                @if (_selectedReward is not null)
                {
                    <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:8px;">
                        <span style="color:var(--pos-text-secondary);">@_selectedReward.Name</span>
                        <span style="color:#22C55E;">@_selectedReward.Value</span>
                    </div>
                }
                <button class="pos-btn-checkout" @onclick="@(() => NavigateTo("karaoke/room-session"))">
                    <i data-lucide="check" style="width:18px;height:18px;"></i> Áp dụng
                </button>
            </div>
        }
        else
        {
            <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);font-size:14px;">
                Tìm thành viên để xem ưu đãi
            </div>
        }
    </div>
</div>

@code {
    private string _searchTerm = "";
    private bool _isSearching;
    private string? _searchMessage;
    private bool _searchError;
    private RewardInfo? _selectedReward;

    // EN: Active member from API search / VI: Thành viên hiện tại từ API tìm kiếm
    private MemberInfo? _activeMember;

    // EN: Visit history — populated when member is found
    // VI: Lịch sử đến — được điền khi tìm thấy thành viên
    // TODO: Wire to member visit history API when available
    private List<VisitInfo> _visitHistory = new();

    // EN: Available rewards — static until rewards API is available
    // VI: Ưu đãi khả dụng — tĩnh cho đến khi có rewards API
    private readonly List<RewardInfo> _rewards = new()
    {
        new("RW1", "Giảm 20% phòng", "-20%", "Áp dụng cho mọi loại phòng", 500),
        new("RW2", "Free 1 giờ", "Miễn phí", "1 giờ Standard miễn phí", 800),
        new("RW3", "Combo F&B", "-50,000₫", "Giảm 50K cho đơn F&B từ 200K", 300),
    };

    // EN: Membership level definitions for tier display / VI: Định nghĩa cấp thành viên để hiển thị hạng
    private Dictionary<int, string> _levelNames = new();

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

        try
        {
            // EN: Pre-load membership levels for tier name lookup / VI: Tải trước cấp thành viên
            var levels = await DataService.GetMembershipLevelsAsync();
            _levelNames = levels.ToDictionary(l => l.LevelNumber, l => l.Name);
        }
        catch { /* EN: Non-critical, tier names will fallback / VI: Không quan trọng, tên hạng sẽ dùng giá trị mặc định */ }
    }

    private async Task HandleSearchKeyDown(Microsoft.AspNetCore.Components.Web.KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
            await SearchMember();
    }

    /// <summary>
    /// EN: Search for member via API using phone or card ID.
    /// VI: Tìm kiếm thành viên qua API theo SĐT hoặc mã thẻ.
    /// </summary>
    private async Task SearchMember()
    {
        if (string.IsNullOrWhiteSpace(_searchTerm) || _isSearching) return;

        _isSearching = true;
        _searchMessage = null;
        _activeMember = null;
        _visitHistory = new();
        _selectedReward = null;
        StateHasChanged();

        try
        {
            var members = await DataService.GetMembersAsync(_searchTerm);

            if (members.Any())
            {
                var m = members.First();
                var tierName = _levelNames.GetValueOrDefault(m.CurrentLevel) ?? m.LevelName ?? $"Level {m.CurrentLevel}";

                // EN: Calculate discount based on tier level / VI: Tính giảm giá dựa trên cấp hạng
                var discount = m.CurrentLevel switch
                {
                    >= 4 => 20,    // Diamond+
                    3 => 15,       // Gold
                    2 => 10,       // Silver
                    _ => 5         // Bronze/Basic
                };

                _activeMember = new MemberInfo(
                    m.DisplayName ?? $"Thành viên #{m.Id.ToString()[..8]}",
                    m.Phone ?? "N/A",
                    tierName,
                    m.CurrentExp,
                    m.TotalExpEarned / 100,  // EN: Approximate visit count / VI: Ước lượng số lần đến
                    discount,
                    $"MBR-{m.Id.ToString()[..8].ToUpper()}",
                    m.CreatedAt.ToString("dd/MM/yyyy")
                );

                _searchMessage = null;
            }
            else
            {
                _searchMessage = "Không tìm thấy thành viên. Vui lòng kiểm tra lại SĐT hoặc mã thẻ.";
                _searchError = true;
            }
        }
        catch (Exception ex)
        {
            _searchMessage = $"Lỗi tìm kiếm: {ex.Message}";
            _searchError = true;
        }
        finally
        {
            _isSearching = false;
        }
    }

    private static string GetTierBg(string t) => t.ToLower() switch
    {
        var s when s.Contains("gold") => "rgba(245,158,11,.2)",
        var s when s.Contains("platinum") || s.Contains("silver") => "rgba(168,162,158,.2)",
        var s when s.Contains("diamond") => "rgba(59,130,246,.2)",
        _ => "rgba(255,255,255,.1)"
    };

    private static string GetTierFg(string t) => t.ToLower() switch
    {
        var s when s.Contains("gold") => "#F59E0B",
        var s when s.Contains("platinum") || s.Contains("silver") => "#A8A29E",
        var s when s.Contains("diamond") => "#3B82F6",
        _ => "#ADADB0"
    };

    private record MemberInfo(string Name, string Phone, string Tier, int Points, int Visits, int Discount, string CardId, string JoinDate);
    private record VisitInfo(string Room, string Date, string Duration, decimal Total, int Points);
    private record RewardInfo(string Id, string Name, string Value, string Description, int PointCost);
}
