@using Microsoft.AspNetCore.Identity
@using RobotNet.IdentityServer.Data
@using MudBlazor
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components
@using Microsoft.EntityFrameworkCore
@using System.Threading
@using RobotNet.IdentityServer.Services
@using System.Security.Claims

@implements IDisposable
@inherits LayoutComponentBase

@inject RobotNet.IdentityServer.Services.IdentityService IdentityService
@inject RobotNet.IdentityServer.Services.UserInfoService UserInfoService

@inject NavigationManager NavigationManager
@inject AuthenticationStateProvider AuthenticationStateProvider

@inject RoleManager<ApplicationRole> RoleManager




<div class="top-row px-4 py-3 bg-gradient-to-r from-blue-400 to-purple-500 flex items-center">
    <a class="navbar-brand text-white font-bold text-lg" href="">User Management</a>
    <button class="navbar-toggler md:hidden">
        <span class="mdi mdi-menu text-white text-2xl"></span>
    </button>
</div>

<div class="nav-scrollable">
    <nav class="nav flex-column p-2 space-y-2">
        <AuthorizeView>
            <Authorized>
                <div class="nav-item">
                    <NavLink class="nav-link flex items-center space-x-3 text-gray-200 hover:bg-blue-500/20 rounded-lg p-2 transition-all duration-300" href="Account/Usermanager">
                        <span class="mdi mdi-account-cog text-xl"></span>
                        <span class="text-nav">User Info Management</span>
                    </NavLink>
                </div>
            </Authorized>
        </AuthorizeView>

        <AuthorizeView Roles="Administrator">
            <Authorized>
                <div class="nav-item">
                    <NavLink class="nav-link flex items-center space-x-3 text-gray-200 hover:bg-blue-500/20 rounded-lg p-2 transition-all duration-300" href="Account/Rolemanager">
                        <span class="mdi mdi-account-cog text-xl"></span>
                        <span class="text-nav">Role Manager</span>
                    </NavLink>
                </div>
                <div class="nav-item">
                    <NavLink class="nav-link flex items-center space-x-3 text-gray-200 hover:bg-blue-500/20 rounded-lg p-2 transition-all duration-300" href="/Account/OpenIdDictManager">
                        <span class="mdi mdi-database-import-outline text-xl"></span>
                        <span class="text-nav">OpenIdDict</span>
                    </NavLink>
                </div>
            </Authorized>
        </AuthorizeView>
        <AuthorizeView>

            <NotAuthorized>
                <div class="nav-item">
                    <NavLink class="nav-link flex items-center space-x-3 text-gray-200 hover:bg-blue-500/20 rounded-lg p-2 transition-all duration-300" href="Account/Login">
                        <span class="mdi mdi-account-arrow-right text-xl"></span>
                        <span class="text-nav">Login</span>
                    </NavLink>
                </div>
                <div class="nav-item">
                    <NavLink class="nav-link flex items-center space-x-3 text-gray-200 hover:bg-blue-500/20 rounded-lg p-2 transition-all duration-300" href="Account/Register">
                        <span class="mdi mdi-account-plus text-xl"></span>
                        <span class="text-nav">Register</span>
                    </NavLink>
                </div>
            </NotAuthorized>
        </AuthorizeView>
    </nav>
    <AuthorizeView>
        <Authorized>
            <div class="user-profile mt-auto">
                <div class="user-profile-inner">
                    <div class="avatar">
                        @if (string.IsNullOrEmpty(userImageUrl))
                        {
                            <div class="avatar-placeholder">
                                <span class="mdi mdi-account text-3xl"></span>
                            </div>
                        }
                        else
                        {
                            <img src="@userImageUrl" alt="User Avatar" class="avatar-image" />
                        }
                    </div>
                    <div class="user-info">
                        <div class="username">@userName</div>
                        <div class="user-email">@userEmail</div>
                    </div>
                    <form action="Account/Logout" method="post" class="logout-form">
                        <AntiforgeryToken />
                        <input type="hidden" name="ReturnUrl" value="@currentUrl" />
                        <button type="submit" class="logout-button" title="Logout">
                            <span class=" mdi mdi-account-arrow-left text-xl"></span>
                        </button>
                    </form>
                </div>
            </div>
        </Authorized>
    </AuthorizeView>
</div>
@code {
    private Func<Task>? _userInfoChangedHandler;
    private string cacheBuster = "";
    private string? currentUrl;
    private ApplicationUser? currentUser;

    @inject UserManager<ApplicationUser> UserManager
    @inject AuthenticationStateProvider AuthenticationStateProvider

    private string userName = string.Empty;
    private string userEmail = string.Empty;
    private string userImageUrl = string.Empty;

    protected override async Task OnInitializedAsync()
    {

        currentUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
        NavigationManager.LocationChanged += OnLocationChanged;

        _userInfoChangedHandler = async () =>
        {
            await InvokeAsync(async () =>
            {
                await LoadUserInfoAsync();
                StateHasChanged();
            });
        };
        UserInfoService.RegisterHandler(_userInfoChangedHandler);
        await LoadUserInfoAsync();
    }

    private async Task UserInfoChangedHandler()
    {
        await LoadUserInfoAsync();


        await InvokeAsync(() =>
        {
            cacheBuster = $"?v={DateTime.Now.Ticks}";
            StateHasChanged();
        });
    }

    private async Task LoadUserInfoAsync()
    {
        try
        {
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;

            if (user?.Identity?.IsAuthenticated == true)
            {
                var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
                if (!string.IsNullOrEmpty(userId))
                {

                    currentUser = await IdentityService.GetUserByIdAsync(userId);
                    if (currentUser != null)
                    {
                        userName = currentUser.UserName ?? string.Empty; ;
                        userEmail = currentUser.Email ?? string.Empty; ;

                        if (currentUser.AvatarImage != null)
                        {

                            userImageUrl = $"data:{currentUser.AvatarContentType ?? "image/jpeg"};base64,{Convert.ToBase64String(currentUser.AvatarImage)}";
                        }
                        else
                        {

                            userImageUrl = "/uploads/avatars/anh.jpg";
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error loading user info: {ex.Message}");
        }
    }



    private void OnLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        InvokeAsync(() =>
    {
        currentUrl = NavigationManager.ToBaseRelativePath(e.Location);
        StateHasChanged();
        return Task.CompletedTask;
    });
    }

    public void Dispose()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;

        if (UserInfoService != null && _userInfoChangedHandler != null)
        {
            UserInfoService.UnregisterHandler(_userInfoChangedHandler);
        }
    }
}