@*
    EN: Spa Customer Profile — Photo, VIP tier badge, points, progress bar, visit history, favorites, rewards.
        Loads real member data from API with appointment history.
    VI: Ho so khach Spa — Anh, badge hang VIP, diem, thanh tien trinh, lich su ghe, yeu thich, phan thuong.
        Tai du lieu thanh vien that tu API voi lich su lich hen.
*@
@page "/pos/{ShopId:guid}/spa/customer-profile"
@page "/pos/{ShopId:guid}/spa/customer-profile/{CustomerId:guid}"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;overflow:hidden;">
    @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 || _member == null)
    {
        <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;flex:1;gap:12px;color:var(--pos-text-tertiary);">
            <div>Khong the tai ho so khach hang</div>
            <button style="padding:10px 20px;border-radius:8px;background:var(--pos-orange-primary);border:none;color:#FFF;cursor:pointer;"
                    @onclick="@(() => NavigateTo("spa/customer-lookup"))">
                Tim khach hang
            </button>
        </div>
    }
    else
    {
    @* === PROFILE PANEL (LEFT) / PANEL HO SO (TRAI) === *@
    <div class="pos-product-panel" style="padding:16px;overflow-y:auto;">
        @* EN: Header / VI: Tieu de *@
        <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("spa/customer-lookup"))">
                <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
            </button>
            <span style="font-size:16px;font-weight:700;">Ho so khach hang</span>
        </div>

        @* === PROFILE CARD / THE HO SO === *@
        <div style="background:linear-gradient(135deg,#1A1A1D,#2A2A2E);border-radius:16px;padding:24px;
                    margin-bottom:16px;border:1px solid rgba(245,158,11,.3);text-align:center;">
            <div style="width:72px;height:72px;border-radius:50%;background:var(--pos-orange-primary);display:flex;align-items:center;justify-content:center;margin:0 auto 12px;font-size:28px;font-weight:700;color:#fff;">
                @_memberInitial
            </div>
            <div style="font-size:20px;font-weight:700;">@_memberName</div>
            <div style="font-size:13px;color:var(--pos-text-tertiary);margin-top:2px;">@(_member.Phone ?? "---")</div>
            <span style="display:inline-block;margin-top:8px;padding:4px 16px;border-radius:8px;font-size:12px;font-weight:700;
                         background:@GetLevelBadgeBg(_member.CurrentLevel);color:@GetLevelBadgeColor(_member.CurrentLevel);">
                @(_member.LevelName ?? $"Level {_member.CurrentLevel}")
            </span>

            @* EN: Stats row / VI: Hang thong ke *@
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-top:16px;">
                <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);">@_member.CurrentExp.ToString("N0")</div>
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Diem</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;">@_visitCount</div>
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Luot ghe</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;">@FormatCompact(_totalSpent)</div>
                    <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">Tong chi</div>
                </div>
            </div>

            @* EN: Tier progress / VI: Tien trinh hang *@
            @if (_progress != null)
            {
                <div style="margin-top:16px;">
                    <div style="display:flex;justify-content:space-between;font-size:11px;color:var(--pos-text-tertiary);margin-bottom:4px;">
                        <span>@(_progress.CurrentLevelName ?? $"Lv{_member.CurrentLevel}")</span>
                        <span>@_member.CurrentExp.ToString("N0") / @(_progress.ExpToNextLevel > 0 ? _progress.ExpToNextLevel.ToString("N0") : "MAX") diem</span>
                        <span>@(_progress.NextLevelName ?? "MAX")</span>
                    </div>
                    <div style="height:6px;border-radius:3px;background:rgba(255,255,255,.1);">
                        <div style="height:100%;border-radius:3px;background:linear-gradient(90deg,#F59E0B,#8B5CF6);width:@(_progressPct)%;"></div>
                    </div>
                    @if (_progress.ExpToNextLevel > _member.CurrentExp)
                    {
                        <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:6px;">
                            Con @((_progress.ExpToNextLevel - _member.CurrentExp).ToString("N0")) diem de len hang @(_progress.NextLevelName ?? "tiep theo")
                        </div>
                    }
                </div>
            }
        </div>

        @* === VISIT HISTORY / LICH SU GHE === *@
        <div style="font-size:14px;font-weight:600;margin-bottom:10px;">Lich su ghe gan day</div>
        @if (_appointments.Any())
        {
            @foreach (var appt in _appointments.Take(5))
            {
                <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="sparkles" style="width:18px;height:18px;color:var(--pos-text-tertiary);"></i>
                    </div>
                    <div style="flex:1;">
                        <div style="font-size:13px;font-weight:600;">@(appt.ResourceName ?? "Dich vu")</div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);">@appt.StartTime.ToString("dd/MM/yyyy HH:mm") • @appt.Status</div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:13px;font-weight:600;">
                            @((appt.EndTime - appt.StartTime).TotalMinutes.ToString("0")) phut
                        </div>
                    </div>
                </div>
            }
        }
        else if (_expHistory.Any())
        {
            @foreach (var tx in _expHistory.Take(5))
            {
                <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="sparkles" style="width:18px;height:18px;color:var(--pos-text-tertiary);"></i>
                    </div>
                    <div style="flex:1;">
                        <div style="font-size:13px;font-weight:600;">@(tx.Source ?? "Giao dich")</div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);">@tx.CreatedAt.ToString("dd/MM/yyyy")</div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:11px;color:#22C55E;">+@tx.Points diem</div>
                    </div>
                </div>
            }
        }
        else
        {
            <div style="padding:16px;text-align:center;color:var(--pos-text-tertiary);font-size:13px;">
                Chua co lich su
            </div>
        }

        @* === FAVORITE SERVICES / DICH VU YEU THICH === *@
        @if (_favorites.Any())
        {
            <div style="font-size:14px;font-weight:600;margin:16px 0 10px;">Dich vu yeu thich</div>
            <div style="display:flex;flex-wrap:wrap;gap:8px;">
                @foreach (var fav in _favorites)
                {
                    <span style="padding:6px 14px;border-radius:20px;font-size:12px;font-weight:500;
                                 background:rgba(255,92,0,.1);color:var(--pos-orange-primary);
                                 border:1px solid rgba(255,92,0,.2);">
                        @fav
                    </span>
                }
            </div>
        }
    </div>

    @* === REWARDS PANEL (RIGHT) / PANEL PHAN THUONG (PHAI) === *@
    <div class="pos-cart-panel">
        <div class="pos-cart-header">
            <span class="pos-cart-header__title">Phan thuong</span>
        </div>

        <div class="pos-cart-items" style="padding:12px;">
            @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:@(reward.PointCost <= _member.CurrentExp ? "#22C55E" : "var(--pos-text-tertiary)");margin-top:2px;">
                        Can @reward.PointCost diem @(reward.PointCost <= _member.CurrentExp ? "(Du diem)" : "")
                    </div>
                </div>
            }
        </div>

        <div class="pos-cart-footer">
            @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("spa"))">
                <i data-lucide="check" style="width:18px;height:18px;"></i> Chon khach hang
            </button>
        </div>
    </div>
    }
</div>

@code {
    // EN: Customer ID from route parameter / VI: ID khach hang tu route parameter
    [Parameter] public Guid CustomerId { get; set; }

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

    // EN: Member data from API / VI: Du lieu thanh vien tu API
    private WebClientTpos.Client.Services.PosDataService.MemberInfo? _member;
    private WebClientTpos.Client.Services.PosDataService.MemberProgressInfo? _progress;
    private List<WebClientTpos.Client.Services.PosDataService.ExpTransactionInfo> _expHistory = new();
    private List<WebClientTpos.Client.Services.PosDataService.AppointmentInfo> _appointments = new();

    // EN: Derived display values / VI: Gia tri hien thi
    private string _memberName = "";
    private string _memberInitial = "?";
    private int _visitCount;
    private decimal _totalSpent;
    private int _progressPct;
    private List<string> _favorites = new();

    private RewardInfo? _selectedReward;

    // EN: Available rewards (config-based) / VI: Phan thuong kha dung (cau hinh)
    private readonly List<RewardInfo> _rewards = new()
    {
        new("RW1", "Giam 20% dich vu", "-20%", "Ap dung cho moi dich vu don le", 500),
        new("RW2", "Free Massage chan", "Mien phi", "1 lan Massage chan 45 phut mien phi", 800),
        new("RW3", "Giam 100K", "-100,000d", "Giam 100K cho hoa don tu 500K", 400),
        new("RW4", "Nang hang dich vu", "Upgrade", "Nang Facial co ban len Facial collagen", 600),
    };

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

        // EN: If no CustomerId provided, redirect to lookup / VI: Neu khong co CustomerId, chuyen den tim kiem
        if (CustomerId == Guid.Empty)
        {
            // EN: Try to get first member as demo / VI: Thu lay thanh vien dau tien lam demo
            try
            {
                var members = await DataService.GetMembersAsync();
                if (members.Any())
                {
                    _member = members.First();
                    CustomerId = _member.Id;
                }
                else
                {
                    NavigateTo("spa/customer-lookup");
                    return;
                }
            }
            catch
            {
                NavigateTo("spa/customer-lookup");
                return;
            }
        }

        try
        {
            // EN: Load member by ID — search in member list / VI: Tai thanh vien theo ID — tim trong danh sach
            if (_member == null)
            {
                var members = await DataService.GetMembersAsync();
                _member = members.FirstOrDefault(m => m.Id == CustomerId);
            }

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

            // EN: Set display values / VI: Dat gia tri hien thi
            _memberName = _member.DisplayName ?? $"Thanh vien #{_member.Id.ToString()[..8]}";
            _memberInitial = string.IsNullOrEmpty(_memberName) ? "?" : _memberName[..1].ToUpper();

            // EN: Load progress info / VI: Tai thong tin tien trinh
            try
            {
                _progress = await DataService.GetMemberProgressAsync(_member.Id);
                if (_progress != null && _progress.ExpToNextLevel > 0)
                {
                    _progressPct = Math.Min(100, (int)((decimal)_member.CurrentExp / _progress.ExpToNextLevel * 100));
                }
            }
            catch { /* EN: Non-critical / VI: Khong quan trong */ }

            // EN: Load experience history / VI: Tai lich su kinh nghiem
            try
            {
                _expHistory = await DataService.GetExperienceHistoryAsync(_member.Id);
                _visitCount = _expHistory.Count;
                _totalSpent = _expHistory.Sum(e => e.Points) * 10_000m; // EN: Rough estimate / VI: Uoc tinh
            }
            catch { /* EN: Non-critical / VI: Khong quan trong */ }

            // EN: Load appointment history / VI: Tai lich su lich hen
            try
            {
                var allAppts = await DataService.GetAppointmentsAsync(ShopId);
                _appointments = allAppts
                    .Where(a => a.CustomerId == CustomerId)
                    .OrderByDescending(a => a.StartTime)
                    .ToList();

                if (_appointments.Any())
                {
                    _visitCount = Math.Max(_visitCount, _appointments.Count);
                    // EN: Build favorites from most common services / VI: Xay dung yeu thich tu dich vu pho bien
                    _favorites = _appointments
                        .Where(a => !string.IsNullOrEmpty(a.ResourceName))
                        .GroupBy(a => a.ResourceName!)
                        .OrderByDescending(g => g.Count())
                        .Take(4)
                        .Select(g => g.Key)
                        .ToList();
                }
            }
            catch { /* EN: Non-critical / VI: Khong quan trong */ }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private static string GetLevelBadgeBg(int level) => level switch
    {
        >= 4 => "rgba(139,92,246,.2)",
        3 => "rgba(245,158,11,.2)",
        2 => "rgba(192,192,192,.2)",
        _ => "rgba(139,90,43,.2)"
    };

    private static string GetLevelBadgeColor(int level) => level switch
    {
        >= 4 => "#8B5CF6",
        3 => "#F59E0B",
        2 => "#C0C0C0",
        _ => "#8B5A2B"
    };

    private static string FormatCompact(decimal amount)
    {
        if (amount >= 1_000_000) return $"{amount / 1_000_000:0.#}M";
        if (amount >= 1_000) return $"{amount / 1_000:0.#}K";
        return amount.ToString("N0");
    }

    private record RewardInfo(string Id, string Name, string Value, string Description, int PointCost);
}
