@page "/admin/users"
@layout AdminLayout
@inherits AdminBase
@inject WebClientTpos.Client.Services.IamApiService IamService
@inject IDialogService DialogService
@inject ISnackbar Snackbar
@using WebClientTpos.Client.Services
@using MudBlazor

@*
    EN: User Management — list users, view details, assign/remove roles.
    VI: Quản lý người dùng — danh sách, xem chi tiết, gán/xóa vai trò.
*@

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

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Người dùng</h1>
        <p class="admin-topbar__subtitle">Quản lý tài khoản và phân quyền người dùng</p>
    </div>
    <div class="admin-topbar__right">
        <div style="display:flex;align-items:center;gap:12px;">
            <div style="position:relative;">
                <i data-lucide="search" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                <input type="text" @bind="_searchQuery" @bind:event="oninput" @onkeyup="OnSearchChanged"
                       placeholder="Tìm theo tên hoặc email..."
                       style="padding:8px 12px 8px 36px;border-radius:10px;border:1px solid var(--admin-border);background:var(--admin-bg-interactive);color:var(--admin-text-primary);font-size:13px;width:240px;outline:none;" />
            </div>
            <span style="font-size:12px;color:var(--admin-text-tertiary);">
                @_totalCount người dùng
            </span>
        </div>
    </div>
</div>

@* ═══ CONTENT ═══ *@
@if (_loading)
{
    <div class="admin-content" style="display:flex;align-items:center;justify-content:center;min-height:300px;">
        <MudProgressCircular Color="Color.Primary" Indeterminate="true" />
    </div>
}
else if (!_users.Any())
{
    <div class="admin-content" style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:300px;gap:12px;">
        <i data-lucide="users" style="width:48px;height:48px;color:var(--admin-text-tertiary);"></i>
        <span style="color:var(--admin-text-tertiary);font-size:15px;">Chưa có người dùng nào</span>
        <span style="color:var(--admin-text-tertiary);font-size:13px;">Người dùng sẽ xuất hiện khi đăng ký tài khoản</span>
    </div>
}
else
{
    <div class="admin-content" style="display:flex;gap:24px;">
        @* LEFT: User list *@
        <div style="flex:1;display:flex;flex-direction:column;gap:8px;">
            @foreach (var user in _users)
            {
                <button class="admin-role-card @(_selectedId == user.Id ? "admin-role-card--active" : "")"
                        @onclick="@(() => SelectUser(user))">
                    <div style="display:flex;align-items:center;gap:12px;flex:1;">
                        <div style="width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg, #FF5C00 0%, #FF8A3D 100%);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:#fff;flex-shrink:0;">
                            @GetInitials(user)
                        </div>
                        <div style="text-align:left;min-width:0;">
                            <div style="font-size:14px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                                @(string.IsNullOrEmpty(user.FullName) ? user.Email : user.FullName)
                            </div>
                            <div style="font-size:11px;color:var(--admin-text-tertiary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                                @user.Email
                            </div>
                        </div>
                    </div>
                    <div style="display:flex;align-items:center;gap:6px;">
                        @if (!string.IsNullOrEmpty(user.Status))
                        {
                            <span style="font-size:10px;padding:2px 8px;border-radius:12px;
                                background:@(user.Status?.ToLower() == "active" ? "rgba(34,197,94,0.15)" : "rgba(239,68,68,0.15)");
                                color:@(user.Status?.ToLower() == "active" ? "#22C55E" : "#EF4444");">
                                @user.Status
                            </span>
                        }
                        <i data-lucide="chevron-right" style="width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                    </div>
                </button>
            }

            @* Pagination *@
            @if (_totalCount > _pageSize)
            {
                <div style="display:flex;justify-content:center;gap:8px;margin-top:12px;">
                    <button class="admin-btn-secondary" disabled="@(_currentPage <= 1)" @onclick="PreviousPage"
                            style="font-size:12px;padding:6px 12px;">
                        ← Trước
                    </button>
                    <span style="font-size:12px;color:var(--admin-text-tertiary);align-self:center;">
                        Trang @_currentPage / @TotalPages
                    </span>
                    <button class="admin-btn-secondary" disabled="@(_currentPage >= TotalPages)" @onclick="NextPage"
                            style="font-size:12px;padding:6px 12px;">
                        Sau →
                    </button>
                </div>
            }
        </div>

        @* RIGHT: User Details *@
        <div style="width:420px;display:flex;flex-direction:column;gap:16px;">
            @if (_selectedUser != null)
            {
                @* User Info Card *@
                <div class="admin-panel">
                    <div class="admin-panel__header">
                        <h3 class="admin-panel__title">
                            <i data-lucide="user" style="color:var(--admin-orange-primary);"></i>
                            Chi tiết người dùng
                        </h3>
                    </div>
                    <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:16px;">
                        @* Avatar + Name *@
                        <div style="display:flex;align-items:center;gap:16px;">
                            <div style="width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg, #FF5C00 0%, #FF8A3D 100%);display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:700;color:#fff;">
                                @GetInitials(_selectedUser)
                            </div>
                            <div>
                                <div style="font-size:16px;font-weight:700;">
                                    @(string.IsNullOrEmpty(_selectedUser.FullName) ? _selectedUser.Email : _selectedUser.FullName)
                                </div>
                                <div style="font-size:13px;color:var(--admin-text-tertiary);">@_selectedUser.Email</div>
                            </div>
                        </div>

                        @* Stats Grid *@
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                            <div class="admin-store-stat">
                                <div class="admin-store-stat__value" style="font-size:13px;">
                                    @(_selectedUser.Status ?? "N/A")
                                </div>
                                <div class="admin-store-stat__label">Trạng thái</div>
                            </div>
                            <div class="admin-store-stat">
                                <div class="admin-store-stat__value" style="font-size:13px;">
                                    @_selectedUser.CreatedAt.ToString("dd/MM/yy")
                                </div>
                                <div class="admin-store-stat__label">Ngày tạo</div>
                            </div>
                            <div class="admin-store-stat">
                                <div class="admin-store-stat__value" style="font-size:13px;">
                                    @(_selectedUser.LastLoginAt?.ToString("dd/MM/yy HH:mm") ?? "Chưa đăng nhập")
                                </div>
                                <div class="admin-store-stat__label">Đăng nhập cuối</div>
                            </div>
                            <div class="admin-store-stat">
                                <div class="admin-store-stat__value" style="font-size:13px;">
                                    @_selectedUserRoles.Count
                                </div>
                                <div class="admin-store-stat__label">Vai trò</div>
                            </div>
                        </div>
                    </div>
                </div>

                @* Roles Card *@
                <div class="admin-panel">
                    <div class="admin-panel__header" style="display:flex;justify-content:space-between;align-items:center;">
                        <h3 class="admin-panel__title">
                            <i data-lucide="shield" style="color:var(--admin-orange-primary);"></i>
                            Vai trò
                        </h3>
                    </div>
                    <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:12px;">
                        @* Assigned roles *@
                        @if (_selectedUserRoles.Any())
                        {
                            @foreach (var role in _selectedUserRoles)
                            {
                                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 12px;background:var(--admin-bg-interactive);border-radius:10px;">
                                    <div style="display:flex;align-items:center;gap:8px;">
                                        <i data-lucide="shield-check" style="width:16px;height:16px;color:#22C55E;"></i>
                                        <span style="font-size:13px;font-weight:500;">@role</span>
                                    </div>
                                    <button @onclick="@(() => RemoveRole(role))" title="Xóa vai trò"
                                            style="background:none;border:none;cursor:pointer;padding:4px;border-radius:6px;color:var(--admin-text-tertiary);"
                                            @onmouseover="@(e => {})" >
                                        <i data-lucide="x" style="width:14px;height:14px;color:#EF4444;"></i>
                                    </button>
                                </div>
                            }
                        }
                        else
                        {
                            <div style="text-align:center;padding:12px;color:var(--admin-text-tertiary);font-size:13px;">
                                Chưa có vai trò nào
                            </div>
                        }

                        @* Assign new role *@
                        <div style="display:flex;gap:8px;margin-top:4px;">
                            <select @bind="_roleToAssign" style="flex:1;padding:8px 12px;border-radius:10px;border:1px solid var(--admin-border);background:var(--admin-bg-interactive);color:var(--admin-text-primary);font-size:13px;">
                                <option value="">-- Chọn vai trò --</option>
                                @foreach (var role in _availableRoles.Where(r => !_selectedUserRoles.Contains(r.Name)))
                                {
                                    <option value="@role.Name">@role.Name</option>
                                }
                            </select>
                            <button class="admin-btn-primary" @onclick="AssignRole"
                                    disabled="@(string.IsNullOrEmpty(_roleToAssign))"
                                    style="font-size:13px;padding:8px 16px;white-space:nowrap;">
                                <i data-lucide="plus" style="width:14px;height:14px;"></i>
                                Gán
                            </button>
                        </div>
                    </div>
                </div>

                @* Actions *@
                <div style="display:flex;gap:8px;">
                    <button class="admin-btn-secondary" @onclick="DeactivateUser"
                            style="flex:1;font-size:13px;padding:8px 16px;color:#EF4444;border-color:rgba(239,68,68,0.3);">
                        <i data-lucide="user-x" style="width:14px;height:14px;"></i>
                        Vô hiệu hóa
                    </button>
                </div>
            }
            else
            {
                <div class="admin-panel">
                    <div class="admin-panel__body" style="text-align:center;padding:48px 20px;">
                        <i data-lucide="mouse-pointer-click" style="width:40px;height:40px;color:var(--admin-text-tertiary);margin-bottom:12px;"></i>
                        <p style="color:var(--admin-text-tertiary);font-size:14px;">Chọn một người dùng để xem chi tiết</p>
                    </div>
                </div>
            }
        </div>
    </div>
}

@code {
    private bool _loading = true;
    private Guid? _selectedId;
    private IamApiService.UserListDto? _selectedUser;
    private List<IamApiService.UserListDto> _users = new();
    private List<string> _selectedUserRoles = new();
    private List<IamApiService.RoleDto> _availableRoles = new();
    private string _searchQuery = string.Empty;
    private string _roleToAssign = string.Empty;
    private int _currentPage = 1;
    private int _pageSize = 20;
    private int _totalCount = 0;
    private int TotalPages => Math.Max(1, (int)Math.Ceiling((double)_totalCount / _pageSize));

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

    private async Task LoadData()
    {
        _loading = true;
        try
        {
            var (users, total) = await IamService.GetUsersAsync(_currentPage, _pageSize);
            _users = users;
            _totalCount = total;
            _availableRoles = await IamService.GetRolesAsync();

            // EN: Auto-select first user if none selected
            // VI: Tự động chọn user đầu tiên nếu chưa chọn
            if (_selectedId == null && _users.Any())
            {
                await SelectUser(_users.First());
            }
        }
        catch { _users = new(); }
        finally { _loading = false; }
    }

    private async Task SelectUser(IamApiService.UserListDto user)
    {
        _selectedId = user.Id;
        _selectedUser = user;
        _roleToAssign = string.Empty;

        // EN: Load user's roles
        // VI: Tải danh sách roles của user
        try { _selectedUserRoles = await IamService.GetUserRolesAsync(user.Id); }
        catch { _selectedUserRoles = new(); }
    }

    private async Task AssignRole()
    {
        if (string.IsNullOrEmpty(_roleToAssign) || _selectedUser == null) return;
        var (success, error) = await IamService.AssignRoleAsync(_selectedUser.Id, _roleToAssign);
        if (success)
        {
            Snackbar.Add($"Đã gán vai trò '{_roleToAssign}'", Severity.Success);
            _selectedUserRoles = await IamService.GetUserRolesAsync(_selectedUser.Id);
            _roleToAssign = string.Empty;
        }
        else
        {
            Snackbar.Add(error ?? "Gán vai trò thất bại", Severity.Error);
        }
    }

    private async Task RemoveRole(string roleName)
    {
        if (_selectedUser == null) return;
        var (success, error) = await IamService.RemoveRoleAsync(_selectedUser.Id, roleName);
        if (success)
        {
            Snackbar.Add($"Đã xóa vai trò '{roleName}'", Severity.Success);
            _selectedUserRoles = await IamService.GetUserRolesAsync(_selectedUser.Id);
        }
        else
        {
            Snackbar.Add(error ?? "Xóa vai trò thất bại", Severity.Error);
        }
    }

    private async Task DeactivateUser()
    {
        if (_selectedUser == null) return;

        // EN: Confirm before deactivating
        // VI: Xác nhận trước khi vô hiệu hóa
        var result = await DialogService.ShowMessageBox(
            "Vô hiệu hóa người dùng",
            $"Bạn có chắc muốn vô hiệu hóa tài khoản '{_selectedUser.Email}'?",
            yesText: "Vô hiệu hóa", cancelText: "Hủy");

        if (result == true)
        {
            var (success, error) = await IamService.DeleteUserAsync(_selectedUser.Id);
            if (success)
            {
                Snackbar.Add("Đã vô hiệu hóa người dùng", Severity.Success);
                await LoadData();
                _selectedUser = null;
                _selectedId = null;
            }
            else
            {
                Snackbar.Add(error ?? "Vô hiệu hóa thất bại", Severity.Error);
            }
        }
    }

    private async Task OnSearchChanged()
    {
        // EN: Simple client-side filter (for now); swap to server-side later
        // VI: Lọc phía client (tạm thời); chuyển sang server-side sau
        _currentPage = 1;
        await LoadData();
    }

    private async Task PreviousPage()
    {
        if (_currentPage > 1) { _currentPage--; await LoadData(); }
    }

    private async Task NextPage()
    {
        if (_currentPage < TotalPages) { _currentPage++; await LoadData(); }
    }

    private static string GetInitials(IamApiService.UserListDto user)
    {
        if (!string.IsNullOrEmpty(user.FirstName) && !string.IsNullOrEmpty(user.LastName))
            return $"{user.FirstName[0]}{user.LastName[0]}".ToUpper();
        if (!string.IsNullOrEmpty(user.Email))
            return user.Email[..Math.Min(2, user.Email.Length)].ToUpper();
        return "??";
    }
}
