@*
    EN: Spa Customer Lookup — Search by phone/name, results with VIP tier, last visit, create new customer.
    VI: Tra cứu khách Spa — Tìm theo SĐT/tên, kết quả với hạng VIP, lần ghé cuối, tạo khách mới.
*@
@page "/pos/{ShopId:guid}/spa/customer-lookup"
@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("spa"))">
            <i data-lucide="arrow-left" style="width:16px;height:16px;display:inline;"></i>
        </button>
        <span style="font-size:16px;font-weight:700;">Tra cứu khách hàng</span>
    </div>

    @* ═══ SEARCH BAR / THANH TÌM KIẾM ═══ *@
    <div style="padding:16px;flex-shrink:0;">
        <div style="display:flex;gap:8px;">
            <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 tên khách hàng..." @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 20px;border-radius:var(--pos-radius);background:var(--pos-orange-primary);
                           border:none;color:#FFF;cursor:pointer;font-size:13px;font-weight:600;"
                    @onclick="SearchCustomers" disabled="@_isSearching">
                @(_isSearching ? "Đang tìm..." : "Tìm kiếm")
            </button>
        </div>
    </div>

    @* ═══ SEARCH RESULTS / KẾT QUẢ TÌM KIẾM ═══ *@
    <div style="flex:1;overflow-y:auto;padding:0 16px 16px;">
        @if (_isSearching)
        {
            <div style="display:flex;align-items:center;justify-content:center;padding:40px 0;color:var(--pos-text-tertiary);">
                Đang tìm kiếm...
            </div>
        }
        else if (_searchPerformed && !_customers.Any())
        {
            <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:40px 0;color:var(--pos-text-tertiary);">
                <i data-lucide="search-x" style="width:48px;height:48px;margin-bottom:12px;opacity:0.3;"></i>
                <div style="font-size:14px;font-weight:600;">Không tìm thấy khách hàng</div>
                <div style="font-size:12px;margin-top:4px;">Thử tìm với từ khóa khác hoặc tạo khách mới</div>
            </div>
        }
        else if (_searchError is not null)
        {
            <div style="display:flex;align-items:center;justify-content:center;padding:40px 0;color:var(--pos-danger);">
                @_searchError
            </div>
        }
        else
        {
        <div style="display:flex;flex-direction:column;gap:8px;">
            @foreach (var customer in _customers)
            {
                <div style="display:flex;align-items:center;gap:14px;padding:14px 16px;
                            background:var(--pos-bg-elevated);border-radius:var(--pos-radius);
                            cursor:pointer;border:1px solid var(--pos-border-subtle);"
                     @onclick="@(() => NavigateTo("spa/customer-profile"))">
                    @* EN: Avatar / VI: Ảnh đại diện *@
                    <div style="width:48px;height:48px;border-radius:50%;background:@GetTierBg(customer.Tier);
                                display:flex;align-items:center;justify-content:center;flex-shrink:0;
                                font-size:18px;font-weight:700;color:@GetTierFg(customer.Tier);">
                        @customer.Name[..1]
                    </div>

                    @* EN: Customer info / VI: Thông tin khách *@
                    <div style="flex:1;min-width:0;">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <span style="font-size:14px;font-weight:600;">@customer.Name</span>
                            <span style="font-size:11px;padding:2px 8px;border-radius:5px;font-weight:600;
                                         background:@GetTierBg(customer.Tier);color:@GetTierFg(customer.Tier);">
                                @customer.Tier
                            </span>
                        </div>
                        <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:2px;">
                            <i data-lucide="phone" style="width:11px;height:11px;display:inline;"></i> @customer.Phone
                        </div>
                        <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:2px;">
                            Lần ghé cuối: @customer.LastVisit • @customer.TotalVisits lần ghé
                        </div>
                    </div>

                    @* EN: Arrow / VI: Mũi tên *@
                    <i data-lucide="chevron-right" style="width:18px;height:18px;color:var(--pos-text-tertiary);flex-shrink:0;"></i>
                </div>
            }
        </div>

        }

        @* ═══ CREATE NEW CUSTOMER / TẠO KHÁCH MỚI ═══ *@
        <div style="margin-top:16px;">
            <button style="width:100%;padding:16px;border-radius:var(--pos-radius);background:var(--pos-bg-elevated);
                           border:2px dashed var(--pos-border-default);color:var(--pos-text-secondary);
                           cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;gap:8px;">
                <i data-lucide="user-plus" style="width:18px;height:18px;"></i>
                Tạo khách mới
            </button>
        </div>
    </div>
</div>

@code {
    // EN: Search state / VI: Trạng thái tìm kiếm
    private string _searchTerm = "";
    private bool _isSearching;
    private bool _searchPerformed;
    private string? _searchError;
    private List<CustomerInfo> _customers = new();

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

    private async Task SearchCustomers()
    {
        if (string.IsNullOrWhiteSpace(_searchTerm)) return;

        _isSearching = true;
        _searchError = null;
        _searchPerformed = false;

        try
        {
            var members = await DataService.SearchCustomersAsync(ShopId, _searchTerm);

            _customers = members.Select(m =>
            {
                var name = m.DisplayName ?? "Khách";
                var phone = m.Phone ?? "";
                // EN: Map level to tier name / VI: Map cấp độ sang tên hạng
                var tier = m.LevelName ?? (m.CurrentLevel switch
                {
                    >= 4 => "Diamond",
                    3 => "Platinum",
                    2 => "Gold",
                    1 => "Silver",
                    _ => "Member"
                });
                var lastVisit = m.CreatedAt.ToString("dd/MM/yyyy");
                return new CustomerInfo(name, phone, tier, lastVisit, m.TotalExpEarned);
            }).ToList();

            _searchPerformed = true;
        }
        catch
        {
            _searchError = "Lỗi kết nối. Vui lòng thử lại.";
        }
        finally
        {
            _isSearching = false;
        }
    }

    private static string GetTierBg(string t) => t switch
    {
        "Silver" => "rgba(168,162,158,.2)", "Gold" => "rgba(245,158,11,.2)",
        "Platinum" => "rgba(139,92,246,.2)", "Diamond" => "rgba(59,130,246,.2)",
        _ => "rgba(255,255,255,.1)"
    };

    private static string GetTierFg(string t) => t switch
    {
        "Silver" => "#A8A29E", "Gold" => "#F59E0B",
        "Platinum" => "#8B5CF6", "Diamond" => "#3B82F6", _ => "#ADADB0"
    };

    private record CustomerInfo(string Name, string Phone, string Tier, string LastVisit, int TotalVisits);
}
