@page "/superadmin/users"
@layout SuperAdminLayout
@inherits SuperAdminBase
@inject IamApiService IamApi
@using WebClientTpos.Client.Services

<PageTitle>Người dùng — aPOS Super Admin</PageTitle>

<div class="sa-topbar">
    <div class="sa-topbar__left">
        <h1 class="sa-topbar__title">Quản lý người dùng</h1>
        <p class="sa-topbar__subtitle">Tất cả tài khoản trên nền tảng • Tổng: @_totalCount</p>
    </div>
    <div class="sa-topbar__right">
        <div class="sa-search">
            <i data-lucide="search"></i>
            <input type="text" placeholder="Tìm theo email, tên..." @bind="SearchQuery" @bind:event="oninput" />
        </div>
    </div>
</div>

<div class="sa-content">
    <div class="sa-panel">
        @if (IsLoading)
        {
            <div class="sa-panel__body" style="text-align:center;padding:48px;">
                <p style="color:var(--sa-text-tertiary);">Đang tải...</p>
            </div>
        }
        else if (FilteredUsers.Any())
        {
            <table class="sa-table">
                <thead>
                    <tr>
                        <th>Tên</th>
                        <th>Email</th>
                        <th>Trạng thái</th>
                        <th>Vai trò</th>
                        <th>Ngày tạo</th>
                        <th>Đăng nhập cuối</th>
                        <th>Hành động</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var user in FilteredUsers)
                    {
                        <tr>
                            <td>@(string.IsNullOrEmpty(user.FullName) ? $"{user.FirstName} {user.LastName}".Trim() : user.FullName)</td>
                            <td style="color:var(--sa-text-secondary);">@user.Email</td>
                            <td>
                                <span class="sa-badge @(user.Status?.ToLowerInvariant() == "active" ? "sa-badge--success" : "sa-badge--warning")">
                                    @(user.Status ?? "Active")
                                </span>
                            </td>
                            <td>
                                @if (_userRoles.TryGetValue(user.Id, out var roles) && roles.Any())
                                {
                                    @foreach (var role in roles)
                                    {
                                        <span class="sa-badge sa-badge--info" style="margin-right:4px;">@role</span>
                                    }
                                }
                                else
                                {
                                    <span style="color:var(--sa-text-tertiary);font-size:12px;">—</span>
                                }
                            </td>
                            <td>@user.CreatedAt.ToString("dd/MM/yyyy")</td>
                            <td>@(user.LastLoginAt?.ToString("dd/MM HH:mm") ?? "—")</td>
                            <td>
                                <button class="sa-btn-outline" style="font-size:11px;padding:4px 10px;"
                                        @onclick="@(() => NavigationManager.NavigateTo($"/superadmin/users/{user.Id}"))">
                                    Chi tiết
                                </button>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>

            @if (_totalPages > 1)
            {
                <div style="display:flex;align-items:center;justify-content:center;gap:8px;padding:16px;">
                    <button class="sa-btn-outline" disabled="@(_currentPage <= 1)" @onclick="PrevPage">← Trước</button>
                    <span style="font-size:13px;color:var(--sa-text-secondary);">Trang @_currentPage / @_totalPages</span>
                    <button class="sa-btn-outline" disabled="@(_currentPage >= _totalPages)" @onclick="NextPage">Sau →</button>
                </div>
            }
        }
        else
        {
            <div class="sa-empty"><p>Không tìm thấy người dùng nào</p></div>
        }
    </div>
</div>

@code {
    private List<IamApiService.UserListDto> _users = new();
    private Dictionary<Guid, List<string>> _userRoles = new();
    private int _totalCount = 0;
    private int _currentPage = 1;
    private int _pageSize = 20;
    private int _totalPages => Math.Max(1, (int)Math.Ceiling((double)_totalCount / _pageSize));

    private IEnumerable<IamApiService.UserListDto> FilteredUsers =>
        string.IsNullOrEmpty(SearchQuery) ? _users :
        _users.Where(u => (u.FullName ?? $"{u.FirstName} {u.LastName}").Contains(SearchQuery, StringComparison.OrdinalIgnoreCase)
            || u.Email.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase));

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

    private async Task LoadAsync()
    {
        IsLoading = true;
        StateHasChanged();
        var (users, total) = await IamApi.GetUsersAsync(_currentPage, _pageSize);
        _users = users;
        _totalCount = total;
        IsLoading = false;
        StateHasChanged();

        // EN: Load roles for each user in background
        // VI: Load roles cho mỗi user ở background
        foreach (var u in _users)
        {
            var roles = await IamApi.GetUserRolesAsync(u.Id);
            _userRoles[u.Id] = roles;
        }
        StateHasChanged();
    }

    private async Task PrevPage() { _currentPage--; await LoadAsync(); }
    private async Task NextPage() { _currentPage++; await LoadAsync(); }
}
