@page "/userform/edit/{Id}"

@using System.Net.Http.Headers
@using System.Text.Json
@using Microsoft.AspNetCore.Components.Forms

@inject HttpClient _httpClient
@inject NavigationManager Navigation
@inject AuthenticationStateProvider authenticationStateProvider
@inject IToastService toastService

<div class="card mt-4" style="zoom: 90%">
    <div class="card-header text-center">
        <h3 class="card-title">Editar Usuario</h3>
    </div>

    @if (user is not null)
    {
        <EditForm Model="@user" OnValidSubmit="UpdateUser">
            <div class="card-body">
                <DataAnnotationsValidator />
                <ValidationSummary />
                <div class="row">
                    <div class="col-sm-12 col-md-6">
                        <label>Nombre:</label>
                        <InputText @bind-Value="user.FirstName" class="form-control" />
                    </div>
                    <div class="col-sm-12 col-md-6">
                        <label>Apellido:</label>
                        <InputText @bind-Value="user.LastName" class="form-control" />
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-sm-12 col-md-6">
                        <label>Teléfono:</label>
                        <InputText @bind-Value="user.PhoneNumber" class="form-control" />
                    </div>
                    <div class="col-sm-12 col-md-6">
                        <label>Empresa:</label>
                        <InputText @bind-Value="user.CompanyName" class="form-control" />
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-sm-12 col-md-6">
                        <label>Departamento:</label>
                        <InputText @bind-Value="user.Department" class="form-control" />
                    </div>
                    <div class="col-sm-12 col-md-6">
                        <label>Fecha de nacimiento:</label>
                        <InputDate @bind-Value="user.BirthDate" class="form-control" />
                    </div>
                </div>

                <div class="row mt-4">
                    <div class="col-sm-12 col-md-6 d-flex align-items-center">
                        <div class="form-check form-switch">
                            <InputCheckbox id="TwoFactorEnabled" @bind-Value="user.TwoFactorEnabled" class="form-check-input" />
                            <label class="form-check-label ms-2" for="TwoFactorEnabled">Autenticación de dos factores</label>
                        </div>
                    </div>
                    <div class="col-sm-12 col-md-6 d-flex align-items-center">
                        <div class="form-check form-switch">
                            <InputCheckbox id="LockoutEnabled" @bind-Value="user.LockoutEnabled" class="form-check-input" />
                            <label class="form-check-label ms-2" for="LockoutEnabled">Bloqueo de cuenta</label>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card-footer d-flex justify-content-end">
                <button type="submit" class="btn btn-primary me-2">Guardar</button>
                <button type="button" class="btn btn-secondary" @onclick="Cancel">Cancelar</button>
            </div>
        </EditForm>
    }
</div>

@code {
    [Parameter]
    public string id { get; set; } = string.Empty;
    private UserUpdate? user;

    protected override async Task OnInitializedAsync()
    {
        if (id is not null)
        {
            user = await GetUser(id);
        }
    }

    public async Task<UserUpdate?> GetUser(string userId)
    {
        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/GetUserById/" + userId);

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

                    return new UserUpdate
                        {
                            Id = user.Id,
                            UserName = user.UserName,
                            Email = user.Email,
                            LockoutEnabled = user.LockoutEnabled,
                            TwoFactorEnabled = user.TwoFactorEnabled,
                            FirstName = user.FirstName,
                            LastName = user.LastName,
                            PhoneNumber = user.PhoneNumber,
                            CompanyName = user.CompanyName,
                            Department = user.Department,
                            BirthDate = user.BirthDate
                        };
                }
            }
            catch
            {
                return null;
            }
        }
        return null;
    }

    private async Task UpdateUser()
    {
        try
        {
            var userJson = JsonSerializer.Serialize(user);
            var content = new StringContent(userJson, System.Text.Encoding.UTF8, "application/json");
            var response = await _httpClient.PutAsync("/api/Account/UpdateUser/" + id, content);
            if (response.IsSuccessStatusCode)
            {
                toastService.ShowSuccess("Usuario actualizado exitosamente");
                Navigation.NavigateTo("/users");
            }
            else
            {
                var errorMessage = await response.Content.ReadAsStringAsync();
                toastService.ShowError(errorMessage);
            }
        }
        catch (Exception ex)
        {
            toastService.ShowError(ex.Message);
        }
    }

    public void Cancel()
    {
        Navigation.NavigateTo("/users");
    }

    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; }
        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; }

        // Campos personalizados
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? CompanyName { get; set; }
        public string? Department { get; set; }
        public DateTime? BirthDate { get; set; }
    }

    public class UserUpdate
    {
        public string Id { get; set; } = string.Empty;
        public string UserName { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? PhoneNumber { get; set; }
        public string? CompanyName { get; set; }
        public string? Department { get; set; }
        public DateTime? BirthDate { get; set; }
        public bool TwoFactorEnabled { get; set; }
        public bool LockoutEnabled { get; set; }
    }
}