@*
    EN: Spa Staff Assignment — Staff list with photo, name, specialization, rating, availability, skills tags.
    VI: Phân công nhân viên Spa — Danh sách nhân viên với ảnh, tên, chuyên môn, đánh giá, tình trạng, thẻ kỹ năng.
*@
@page "/pos/{ShopId:guid}/spa/staff-assign"
@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;">Chọn nhân viên / Kỹ thuật viên</span>
    </div>

    @* ═══ FILTER TABS / TAB LỌC ═══ *@
    <div style="padding:10px 16px;border-bottom:1px solid var(--pos-border-subtle);display:flex;gap:6px;flex-shrink:0;">
        @foreach (var filter in _filters)
        {
            <button style="padding:6px 14px;border-radius:8px;font-size:12px;cursor:pointer;border:none;
                           background:@(filter == _activeFilter ? "var(--pos-orange-primary)" : "var(--pos-bg-interactive)");
                           color:@(filter == _activeFilter ? "#FFF" : "var(--pos-text-secondary)");"
                    @onclick="() => _activeFilter = filter">
                @filter
            </button>
        }
    </div>

    @* ═══ STAFF LIST / DANH SÁCH NHÂN VIÊN ═══ *@
    <div style="flex:1;overflow-y:auto;padding:16px;">
        @if (_isLoading)
        {
            <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
                Đang tải nhân viên...
            </div>
        }
        else if (_loadError)
        {
            <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
                Không thể tải dữ liệu nhân viên
            </div>
        }
        else if (!_staff.Any())
        {
            <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
                Chưa có nhân viên nào
            </div>
        }
        else
        {
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:12px;">
            @foreach (var staff in FilteredStaff)
            {
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;
                            display:flex;gap:14px;border:2px solid @(_selectedStaff == staff.Id ? "var(--pos-orange-primary)" : "var(--pos-border-subtle)");
                            cursor:pointer;"
                     @onclick="() => _selectedStaff = staff.Id">
                    @* EN: Photo placeholder / VI: Ảnh đại diện *@
                    <div style="position:relative;flex-shrink:0;">
                        <div style="width:56px;height:56px;border-radius:50%;background:var(--pos-bg-interactive);
                                    display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:700;">
                            @staff.Name[..1]
                        </div>
                        <div style="position:absolute;bottom:-2px;right:-2px;width:14px;height:14px;border-radius:50%;
                                    background:@GetStatusColor(staff.Status);border:2px solid var(--pos-bg-elevated);"></div>
                    </div>

                    <div style="flex:1;min-width:0;">
                        @* EN: Name + rating / VI: Tên + đánh giá *@
                        <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px;">
                            <span style="font-size:15px;font-weight:600;">@staff.Name</span>
                            <span style="font-size:12px;padding:2px 8px;border-radius:5px;font-weight:600;
                                         background:@GetStatusBg(staff.Status);color:@GetStatusColor(staff.Status);">
                                @GetStatusLabel(staff.Status)
                            </span>
                        </div>

                        @* EN: Specialization / VI: Chuyên môn *@
                        <div style="font-size:12px;color:var(--pos-text-tertiary);margin-bottom:6px;">
                            @staff.Specialization
                        </div>

                        @* EN: Rating stars / VI: Sao đánh giá *@
                        <div style="display:flex;align-items:center;gap:4px;margin-bottom:8px;">
                            @for (int i = 1; i <= 5; i++)
                            {
                                var starIdx = i;
                                <i data-lucide="star" style="width:14px;height:14px;color:@(starIdx <= staff.Rating ? "#F59E0B" : "var(--pos-border-default)");
                                   fill:@(starIdx <= staff.Rating ? "#F59E0B" : "none");"></i>
                            }
                            <span style="font-size:11px;color:var(--pos-text-tertiary);margin-left:4px;">(@staff.ReviewCount)</span>
                        </div>

                        @* EN: Skill tags / VI: Thẻ kỹ năng *@
                        <div style="display:flex;flex-wrap:wrap;gap:4px;">
                            @foreach (var skill in staff.Skills)
                            {
                                <span style="font-size:10px;padding:3px 8px;border-radius:4px;
                                             background:var(--pos-bg-interactive);color:var(--pos-text-secondary);">
                                    @skill
                                </span>
                            }
                        </div>
                    </div>

                    @* EN: Select indicator / VI: Chỉ báo chọn *@
                    @if (_selectedStaff == staff.Id)
                    {
                        <div style="width:28px;height:28px;border-radius:50%;background:var(--pos-orange-primary);
                                    display:flex;align-items:center;justify-content:center;flex-shrink:0;align-self:center;">
                            <i data-lucide="check" style="width:16px;height:16px;color:#FFF;"></i>
                        </div>
                    }
                </div>
            }
        </div>
        }
    </div>

    @* ═══ FOOTER / CHÂN TRANG ═══ *@
    @if (_selectedStaff is not null)
    {
        <div style="padding:12px 16px;border-top:1px solid var(--pos-border-subtle);flex-shrink:0;">
            <button class="pos-btn-checkout" @onclick="@(() => NavigateTo("spa/appointment-book"))">
                <i data-lucide="check" style="width:18px;height:18px;"></i> Xác nhận chọn nhân viên
            </button>
        </div>
    }
</div>

@code {
    // EN: Loading state / VI: Trạng thái tải
    private bool _isLoading = true;
    private bool _loadError;

    private string _activeFilter = "Tất cả";
    private string? _selectedStaff;
    private readonly string[] _filters = { "Tất cả", "Rảnh", "Đang bận", "Nghỉ giải lao" };

    // EN: Staff from API / VI: Nhân viên từ API
    private List<StaffInfo> _staff = new();

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

        try
        {
            var staffData = await DataService.GetStaffForShopAsync(ShopId);

            _staff = staffData.Select(s =>
            {
                var name = $"{s.FirstName ?? ""} {s.LastName ?? ""}".Trim();
                if (string.IsNullOrEmpty(name)) name = s.EmployeeCode ?? s.Id.ToString()[..8];
                var status = (s.Status?.ToLower()) switch
                {
                    "active" or "available" => "available",
                    "busy" or "occupied" => "busy",
                    "break" or "onbreak" => "break",
                    _ => "available"
                };
                var role = s.Role ?? "Nhân viên";
                // EN: Placeholder skills/rating — staff API does not include these / VI: Kỹ năng/đánh giá giữ chỗ — API nhân viên không có
                return new StaffInfo(s.Id.ToString(), name, role, status, 4, 0, new List<string> { role });
            }).ToList();

            if (_staff.Any())
                _selectedStaff = _staff.First().Id;
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private IEnumerable<StaffInfo> FilteredStaff => _activeFilter switch
    {
        "Rảnh" => _staff.Where(s => s.Status == "available"),
        "Đang bận" => _staff.Where(s => s.Status == "busy"),
        "Nghỉ giải lao" => _staff.Where(s => s.Status == "break"),
        _ => _staff
    };

    private static string GetStatusColor(string s) => s switch
    {
        "available" => "#22C55E", "busy" => "var(--pos-orange-primary)", "break" => "#F59E0B", _ => "#ADADB0"
    };

    private static string GetStatusBg(string s) => s switch
    {
        "available" => "rgba(34,197,94,.15)", "busy" => "rgba(255,92,0,.15)",
        "break" => "rgba(245,158,11,.15)", _ => "var(--pos-bg-interactive)"
    };

    private static string GetStatusLabel(string s) => s switch
    {
        "available" => "Rảnh", "busy" => "Đang bận", "break" => "Nghỉ", _ => s
    };

    private record StaffInfo(string Id, string Name, string Specialization, string Status,
        int Rating, int ReviewCount, List<string> Skills);
}
