using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using phronCare.API.Models.Account;
using phronCare.API.Models.Security; // Importá donde tengas ApplicationUser

namespace phronCare.API.Controllers
{
    [Authorize(Roles = "Admin")]
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<ApplicationUser> _userManager;

        public AccountController(RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
        {
            _roleManager = roleManager;
            _userManager = userManager;
        }

        [HttpGet("GetAllRoles")]
        public IActionResult GetAllRoles()
        {
            var roles = _roleManager.Roles.ToList();
            return Ok(roles);
        }

        [HttpGet("GetRoleById/{id}")]
        public IActionResult GetRoleById(string id)
        {
            var role = _roleManager.Roles.FirstOrDefault(r => r.Id == id.TrimStart('{').TrimEnd('}'));
            return Ok(role);
        }

        [HttpPost("CreateRole")]
        public async Task<IActionResult> CreateRole(Role model)
        {
            var existingRole = await _roleManager.FindByNameAsync(model.Name);
            if (existingRole != null)
            {
                return BadRequest("El rol ya existe.");
            }

            var newRole = new IdentityRole
            {
                Name = model.Name,
                NormalizedName = model.Name.ToUpper(),
                ConcurrencyStamp = Guid.NewGuid().ToString()
            };

            var result = await _roleManager.CreateAsync(newRole);

            if (result.Succeeded)
            {
                return Ok("Rol creado exitosamente.");
            }
            else
            {
                var errors = result.Errors.Select(e => e.Description);
                return BadRequest($"Error al crear el rol: {string.Join(", ", errors)}");
            }
        }

        [HttpPut("UpdateRole/{id}")]
        public async Task<IActionResult> UpdateRole(string id, Role model)
        {
            var role = await _roleManager.FindByIdAsync(id);
            if (role == null)
            {
                return NotFound("Rol no encontrado");
            }

            role.Name = model.Name;
            role.NormalizedName = model.NormalizedName;

            var result = await _roleManager.UpdateAsync(role);

            if (result.Succeeded)
            {
                return Ok("Rol actualizado exitosamente");
            }
            else
            {
                return BadRequest("Error al actualizar el rol");
            }
        }

        [HttpDelete("DeleteRole/{roleId}")]
        public async Task<IActionResult> DeleteRole(string roleId)
        {
            var existingRole = await _roleManager.FindByIdAsync(roleId);
            if (existingRole == null)
            {
                return NotFound("El rol no se encontró.");
            }

            if (existingRole.Name.ToLower() == "admin")
            {
                return BadRequest("No se puede eliminar el rol 'Admin'.");
            }

            var result = await _roleManager.DeleteAsync(existingRole);

            if (result.Succeeded)
            {
                return Ok("El rol se eliminó exitosamente.");
            }
            else
            {
                return BadRequest("Error al eliminar el rol.");
            }
        }

        [HttpGet("GetAllUsers")]
        public IActionResult GetAllUsers()
        {
            var users = _userManager.Users.ToList();
            return Ok(users);
        }

        [HttpGet("GetUserById/{id}")]
        public IActionResult GetUserById(string id)
        {
            var user = _userManager.Users.FirstOrDefault(u => u.Id == id.TrimStart('{').TrimEnd('}'));
            return Ok(user);
        }

        [HttpPut("UpdateUser/{id}")]
        public async Task<IActionResult> UpdateUser(string id, UserUpdate model)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                return NotFound("Usuario no encontrado");
            }

            user.UserName = model.UserName;
            user.NormalizedUserName = model.UserName.ToUpper();
            user.Email = model.Email;
            user.NormalizedEmail = model.Email.ToUpper();
            user.TwoFactorEnabled = model.TwoFactorEnabled;
            user.LockoutEnabled = model.LockoutEnabled;
            user.EmailConfirmed = model.EmailConfirmed;
            // Campos personalizados
            user.FirstName = model.FirstName;
            user.LastName = model.LastName;
            user.PhoneNumber = model.PhoneNumber;
            user.CompanyName = model.CompanyName;
            user.Department = model.Department;
            user.BirthDate = model.BirthDate;
            var result = await _userManager.UpdateAsync(user);

            if (result.Succeeded)
            {
                return Ok("Usuario actualizado exitosamente");
            }
            else
            {
                return BadRequest("Error al actualizar el usuario");
            }
        }

        [HttpDelete("DeleteUser/{userId}")]
        public async Task<IActionResult> DeleteUser(string userId)
        {
            var existingUser = await _userManager.FindByIdAsync(userId);
            if (existingUser == null)
            {
                return NotFound("El usuario no se encontró.");
            }

            if (existingUser.UserName.ToLower() == "superadmin")
            {
                return BadRequest("No se puede eliminar el usuario 'SuperAdmin'.");
            }

            var result = await _userManager.DeleteAsync(existingUser);

            if (result.Succeeded)
            {
                return Ok("El usuario se eliminó exitosamente.");
            }
            else
            {
                return BadRequest("Error al eliminar el usuario.");
            }
        }
    }
}
