using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Aberwyn.Models;


namespace Aberwyn.Controllers
{

    [Authorize(Roles = "Admin")]
    public class AdminController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;

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

        public async Task<IActionResult> Index()
        {
            var users = _userManager.Users.ToList();
            var model = new List<AdminUserViewModel>();

            foreach (var user in users)
            {
                var roles = await _userManager.GetRolesAsync(user);
                model.Add(new AdminUserViewModel
                {
                    UserId = user.Id,
                    Email = user.Email,
                    Roles = roles.ToList()
                });
            }
            var allRoles = _roleManager.Roles.Select(r => r.Name).ToList();
            ViewBag.AllRoles = allRoles;
            return View(model);
        }
        [HttpPost]
        public async Task<IActionResult> CreateUser(string email, string password)
        {
            var user = new ApplicationUser { UserName = email, Email = email };
            var result = await _userManager.CreateAsync(user, password);

            if (result.Succeeded)
            {
                TempData["Message"] = "Användare skapad!";
                return RedirectToAction("Index");
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error.Description);
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        public async Task<IActionResult> AddToRole(string userId, string role)
        {
            var user = await _userManager.FindByIdAsync(userId);
            if (user != null && await _roleManager.RoleExistsAsync(role))
            {
                await _userManager.AddToRoleAsync(user, role);
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        public async Task<IActionResult> RemoveFromRole(string userId, string role)
        {
            var user = await _userManager.FindByIdAsync(userId);
            if (user != null && await _userManager.IsInRoleAsync(user, role))
            {
                await _userManager.RemoveFromRoleAsync(user, role);
            }
            return RedirectToAction("Index");
        }
        [HttpPost]
        public async Task<IActionResult> CreateRole(string roleName)
        {
            if (!string.IsNullOrWhiteSpace(roleName) && !await _roleManager.RoleExistsAsync(roleName))
            {
                await _roleManager.CreateAsync(new IdentityRole(roleName));
            }

            return RedirectToAction("Index");
        }
        [HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult ImportMealsFromProd()
{
    var prodService = MenuService.CreateWithConfig(_configuration, _env, useProdDb: true);
    var devService = new MenuService(_context); // injicerad context används

    var prodMeals = prodService.GetMealsDetailed();

    foreach (var meal in prodMeals)
    {
        // Kopiera utan ID (för att undvika konflikt) och spara
        var newMeal = new Meal
        {
            Name = meal.Name,
            Description = meal.Description,
            ProteinType = meal.ProteinType,
            Category = meal.Category,
            CarbType = meal.CarbType,
            RecipeUrl = meal.RecipeUrl,
            ImageUrl = meal.ImageUrl,
            IsAvailable = meal.IsAvailable,
            CreatedAt = meal.CreatedAt,
            Instructions = meal.Instructions,
            ImageData = meal.ImageData,
            ImageMimeType = meal.ImageMimeType,
            Ingredients = meal.Ingredients.Select(i => new Ingredient
            {
                Quantity = i.Quantity,
                Item = i.Item
            }).ToList()
        };

        devService.SaveOrUpdateMealWithIngredients(newMeal);
    }

    return Content("Import klar!");
}
[HttpPost]
[Authorize(Roles = "Admin")]
[HttpPost]
[Authorize(Roles = "Admin")]
public IActionResult ImportMenusFromProd()
{
    var prodService = MenuService.CreateWithConfig(_configuration, _env, useProdDb: true);
    var devService = new MenuService(_context);

    var allProdMenus = prodService.GetAllWeeklyMenus();
    var allMeals = devService.GetMeals();

            return RedirectToAction("Index");
        }
    }


    public class AdminUserViewModel
    {
        public string UserId { get; set; }
        public string Email { get; set; }
        public List<string> Roles { get; set; }
    }
}
