@page "/users"
@using System.Net.Http.Headers;
@using System.Text.Json;

@inject HttpClient _httpClient
@inject NavigationManager navigation
@inject IToastService toastService

@inject IModalService modalService
@inject AuthenticationStateProvider authenticationStateProvider

<h1>Lista de Usuarios</h1>
<a href="/registration" class="btn btn-dark mb-3">Registrar usuario</a>

@if (users != null && users.Count > 0)
{
    <table class="table table-hover">
        <thead class="table-secondary">
            <tr>
                <th class="text-center align-middle">Nombre completo</th>
                <th class="text-center align-middle">Usuario</th>
                <th class="text-center align-middle">Email</th>
                <th class="text-center align-middle">Teléfono</th>
                <th class="text-center align-middle">Empresa</th>
                <th class="text-center align-middle">Departamento</th>
                <th class="text-center align-middle">Verificado</th>
                <th class="text-center align-middle">2FA</th>
                <th class="text-center align-middle">#Intentos</th>
                <th class="text-center align-middle">Lockout</th>
                <th class="text-center align-middle">Acciones</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var user in users)
            {
                <tr>
                    <td>@user.FullName</td>
                    <td>@user.UserName</td>
                    <td>@user.Email</td>
                    <td>@user.PhoneNumber</td>
                    <td>@user.CompanyName</td>
                    <td>@user.Department</td>
                    <td class="text-center align-middle">@(user.EmailConfirmed ? "✅" : "❌")</td>
                    <td class="text-center align-middle">@(user.TwoFactorEnabled ? "✅" : "❌")</td>
                    <td class="text-center align-middle">@user.AccessFailedCount</td>
                    <td class="text-center align-middle">@(user.LockoutEnabled ? "✅" : "❌")</td>
                    <td>
                        <button class="btn btn-sm btn-primary me-1" @onclick="() => EditUser(user.Id)">
                            <i class="fa fa-pencil"></i>
                        </button>
                        @if (user.UserName.ToLower() != "superdmin")
                        {
                            <button class="btn btn-sm btn-danger me-1" @onclick="() => ConfirmDelete(user.Id)">
                                <i class="fa fa-trash"></i>
                            </button>
                        }
                        <button class="btn btn-sm btn-warning" @onclick="() => RecoveryPassword(user.Email)">
                            <i class="fa fa-user-secret"></i>
                        </button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}
else
{
    <p class="mt-3">Cargando información o no hay usuarios disponibles...</p>
}

@code {
    private List<User> users = new List<User>();
    protected override async Task OnInitializedAsync()
    {
        var customAuthStateProvider = (CustomAuthorizationProvider) authenticationStateProvider;
        var token = await customAuthStateProvider.GetTokenData();
        if (!string.IsNullOrWhiteSpace(token.token))
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
            try
            {
                var response = await _httpClient.GetAsync("/api/Account/GetAllUsers");
                //Console.WriteLine(token.token);
                if (response.IsSuccessStatusCode)
                {
                    var jsonResponse = await response.Content.ReadAsStringAsync();
                    var options = new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        };
                    var deserializedUsers = JsonSerializer.Deserialize<List<User>>(jsonResponse, options);
                    users = deserializedUsers ?? new List<User>();
                }
            }
            catch (Exception ex)
            {
                toastService.ShowError(ex.Message);
            }
        }
    }
    private async Task HandleDeleteConfirmed()
    {
        await RefreshAll();
    }
    // public async Task RefreshAll()
    // {
    //     var response = await _httpClient.GetAsync("/api/Account/GetAllUsers");

    //     if (response.IsSuccessStatusCode)
    //     {
    //         var jsonResponse = await response.Content.ReadAsStringAsync();
    //         var options = new JsonSerializerOptions
    //             {
    //                 PropertyNameCaseInsensitive = true
    //             };
    //         var deserializedUsers = JsonSerializer.Deserialize<List<User>>(jsonResponse, options);
    //         users = deserializedUsers ?? new List<User>();

    //         StateHasChanged();
    //     }
    // }
    public async Task RefreshAll()
    {
        var customAuthStateProvider = (CustomAuthorizationProvider)authenticationStateProvider;
        var token = await customAuthStateProvider.GetTokenData();
        if (!string.IsNullOrWhiteSpace(token.token))
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
        }

        var response = await _httpClient.GetAsync("/api/Account/GetAllUsers");

        if (response.IsSuccessStatusCode)
        {
            var jsonResponse = await response.Content.ReadAsStringAsync();
            var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };
            var deserializedUsers = JsonSerializer.Deserialize<List<User>>(jsonResponse, options);
            users = deserializedUsers ?? new List<User>();

            StateHasChanged();
        }
    }

    public void EditUser(string userId)
    {
        navigation.NavigateTo($"/userform/edit/{userId}");
    }
    public async Task RecoveryPassword(string email)
    {
        var customAuthStateProvider = (CustomAuthorizationProvider)authenticationStateProvider;
        var token = await customAuthStateProvider.GetTokenData();

        if (!string.IsNullOrWhiteSpace(token.token))
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
        }

        string url = $"api/Authentication/forgot-password?email={email}";

        var response = await _httpClient.PostAsync(url, null);
        var message = await response.Content.ReadAsStringAsync();

        if (response.IsSuccessStatusCode)
        {
            toastService.ShowSuccess(message);
        }
        else
        {
            toastService.ShowError(message);
        }
    }
    // public async Task RecoveryPassword(string email)
    // {
    //     string url = $"api/Authentication/forgot-password?email={email}";

    //     var response = await _httpClient.PostAsync(url,null);
    //     var message = await response.Content.ReadAsStringAsync();
    //     if (response.IsSuccessStatusCode)
    //     {
    //         toastService.ShowSuccess(message);
    //     }
    //     else
    //     {
    //         toastService.ShowError(message);
    //     };
    // }
    private void ConfirmDelete(string userId)
    {
        var parameters = new ModalParameters()
                    .Add(nameof(DeleteUser.id), userId)
                    .Add(nameof(DeleteUser.OnDeleteConfirmed), EventCallback.Factory.Create(this, HandleDeleteConfirmed));
        modalService.Show<DeleteUser>("Confirmar Eliminación de Usuario", parameters);
    }
    public class Role
    {
        public string Id { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty;
        public string NormalizedName { get; set; } = string.Empty;
        public string ConcurrencyStamp { get; set; } = string.Empty;
    }
    public class User
    {
        public string Id { get; set; } = string.Empty;
        public string UserName { get; set; } = string.Empty;
        public string NormalizedUserName { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public string NormalizedEmail { get; set; } = string.Empty;
        public bool EmailConfirmed { get; set; }
        public string PasswordHash { get; set; } = string.Empty;
        public string SecurityStamp { get; set; } = string.Empty;
        public string PhoneNumber { get; set; } = string.Empty;
        public bool PhoneNumberConfirmed { get; set; }
        public bool TwoFactorEnabled { get; set; }
        public DateTimeOffset? LockoutEnd { get; set; }
        public bool LockoutEnabled { get; set; }
        public int AccessFailedCount { get; set; }

        // Nuevos campos
        public string FirstName { get; set; } = string.Empty;
        public string LastName { get; set; } = string.Empty;
        public string FullName { get; set; } = string.Empty;
        public string Address { get; set; } = string.Empty;
        public string Department { get; set; } = string.Empty;
        public string CompanyName { get; set; } = string.Empty;
        public DateTime? BirthDate { get; set; }
    }

}