using Microsoft.AspNetCore.Mvc;
using Aberwyn.Models;
using Aberwyn.Data;
using Microsoft.AspNetCore.Authorization;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp;

namespace Aberwyn.Controllers
{
    public class MealController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly IHostEnvironment _env;
        private readonly MenuService _menuService;
        public MealController(MenuService menuService, IConfiguration configuration, IHostEnvironment env)
        {
            _menuService = menuService;
            _configuration = configuration;
            _env = env;
        }
        [HttpGet("/meal")]
        public IActionResult Index()
        {
            return View("Index");
        }
        [HttpGet]
        public IActionResult View(int? id, bool edit = false)
        {
            Meal meal;

            if (id.HasValue)
            {
                meal = _menuService.GetMealById(id.Value);
                if (meal == null)
                    return NotFound();
            }
            else
            {
                meal = new Meal
                {
                    Name = "",
                    Description = "",
                    Ingredients = new List<Ingredient>(),
                    IsAvailable = true,
                    CreatedAt = DateTime.Now
                };
            }
            ViewBag.Categories = _menuService.GetMealCategories()
                .Where(c => c.IsActive)
                .OrderBy(c => c.Name)
                .ToList();
            ViewData["IsEditing"] = edit;
            return View("View", meal);
        }


        [HttpGet]
        [Route("Meal/Tooltip/{id}")]
        public IActionResult Tooltip(int id)
        {
            try
            {
                var service = _menuService;
                var meal = service.GetMealById(id);

                if (meal == null)
                    return Content("<div>Hittade ingen rätt.</div>", "text/html");

                // Se till att Description aldrig är null
                var desc = meal.Description ?? "";

                // Gör en kort beskrivning
                var shortDesc = desc.Length > 100
                    ? desc.Substring(0, 100) + "…"
                    : desc;

                // Bygg upp en enkel HTML-snutt
                var html =
                    $"<div class='tooltip-content'>" +
                    $"  <strong>{meal.Name}</strong><br/>" +
                    (string.IsNullOrWhiteSpace(shortDesc)
                        ? "<em>Ingen beskrivning tillgänglig.</em>"
                        : $"<em>{shortDesc}</em>") +
                    "</div>";

                return Content(html, "text/html");
            }
            catch (Exception ex)
            {
                // För felsökning kan du logga ex.Message, men för tillfället returnera det så vi ser det i devtools
                return StatusCode(500, $"<pre>{ex.Message}</pre>");
            }
        }
        [HttpGet("Meal/Thumbnail/{id}")]
        public IActionResult Thumbnail(int id)
        {
            var meal = _menuService.GetMealById(id);
            if (meal == null || meal.ThumbnailData == null)
                return NotFound();

            return File(meal.ThumbnailData, "image/webp"); // eller image/jpeg om du använder det
        }




        [HttpGet]
        public IActionResult Edit(int? id)
        {
            var service = _menuService;
            var meal = id.HasValue ? service.GetMealById(id.Value) : new Meal();
            return View("Meal", meal);
        }

        [HttpPost]
        public IActionResult SaveMeal(Meal meal, IFormFile ImageFile, string ExistingImageUrl)
        {
            var service = _menuService;

            if (ImageFile != null && ImageFile.Length > 0)
            {
                using var ms = new MemoryStream();
                ImageFile.CopyTo(ms);
                meal.ImageData = ms.ToArray();
                meal.ImageMimeType = ImageFile.ContentType;
                meal.ThumbnailData = GenerateThumbnail(ImageFile);

            }
            else
            {
                var existingMeal = service.GetMealById(meal.Id);
                if (existingMeal != null)
                {
                    meal.ImageData = existingMeal.ImageData;
                    meal.ImageMimeType = existingMeal.ImageMimeType;
                }
            }

            // 🔁 Här är ändringen – använd metoden som även sparar ingredienser
            service.SaveOrUpdateMealWithIngredients(meal);

            return RedirectToAction("View", new { id = meal.Id });
        }


        private byte[] GenerateThumbnail(IFormFile file)
        {
            using var image = SixLabors.ImageSharp.Image.Load(file.OpenReadStream());
            image.Mutate(x => x.Resize(new ResizeOptions
            {
                Mode = ResizeMode.Max,
                Size = new Size(300, 300) // eller vad du vill för korten
            }));

            using var ms = new MemoryStream();
            image.SaveAsWebp(ms); // kräver ImageSharp.Webp-paketet
            return ms.ToArray();
        }

        


        [HttpPost]
        public IActionResult DeleteMeal(int id)
        {
            var service = _menuService;
            //service.DeleteMeal(id);
            return RedirectToAction("Edit"); // eller tillbaka till lista
        }

        [Authorize(Roles = "Admin,Chef")]
        [HttpGet("/meal/categories")]
        public IActionResult Categories()
        {
        var categories = _menuService.GetMealCategories()
            .Select(cat => {
                cat.MealCount = _menuService.GetMealCountForCategory(cat.Id);
                return cat;
            }).ToList();

            return View("MealCategories", categories);
        }

        [Authorize(Roles = "Admin,Chef")]
        [HttpPost("/meal/categories/save")]
        public IActionResult SaveCategory(MealCategory category)
        {
            _menuService.SaveOrUpdateCategory(category);
            return RedirectToAction("Categories");
        }

        [Authorize(Roles = "Admin,Chef")]
        [HttpPost("/meal/categories/delete")]
        public IActionResult DeleteCategory(int id)
        {
            _menuService.DeleteCategory(id);
            return RedirectToAction("Categories");
        }


        [HttpGet("/meal/lab")]
    public IActionResult Lab(int? id)
    {
        if (id.HasValue)
        {
            var entry = _menuService.GetRecipeLabEntryById(id.Value);
            if (entry == null) return NotFound();

            // Hämta versioner först när vi vet att entry finns
            entry.Versions = _menuService.GetLabVersionsForEntry(id.Value);
            return View("Lab", entry);
        }

        // Skapa ett tomt labb-entry för formulär
        var newEntry = new RecipeLabEntry
        {
            Title = "",
            Inspiration = "",
            Notes = "",
            Tags = ""
        };

        return View("Lab", newEntry);
    }
    // Lägg till dessa actions i din MealController

    [HttpPost("/meal/lab/save")]
    public IActionResult SaveLabEntry(RecipeLabEntry entry)
    {
        if (entry.Id == 0)
        {
            // Ny entry
            entry.CreatedAt = DateTime.Now;
            _menuService.AddLabEntry(entry);
        }
        else
        {
            // Uppdatera befintlig
            _menuService.UpdateLabEntry(entry);
        }

        return RedirectToAction("Lab", new { id = entry.Id });
    }
        [HttpPost("/meal/lab/create")]
        public IActionResult CreateLabEntry(RecipeLabEntry entry)
        {
            entry.CreatedAt = DateTime.Now;
            _menuService.AddLabEntry(entry);

            return RedirectToAction("Lab", new { id = entry.Id });
        }

        [HttpPost("/meal/lab/save-ingredients")]
        public IActionResult SaveLabIngredients(int RecipeLabEntryId, List<LabIngredient> Ingredients)
        {
            _menuService.SaveIngredientsForLabEntry(RecipeLabEntryId, Ingredients);
            return RedirectToAction("Lab", new { id = RecipeLabEntryId });
        }


        [HttpPost("/meal/lab/addversion")]
        public IActionResult AddLabVersion(RecipeLabVersion version)
        {
            if (!ModelState.IsValid)
                return RedirectToAction("Lab", new { id = version.RecipeLabEntryId });

            var entry = _menuService.GetRecipeLabEntryById(version.RecipeLabEntryId);
            if (entry == null) return NotFound();

            version.CreatedAt = DateTime.Now;

            // Kopiera nuvarande ingredienser
            var copiedIngredients = entry.Ingredients
                .Select(i => new LabVersionIngredient
                {
                    Quantity = i.Quantity,
                    Item = i.Item
                })
                .ToList();

            _menuService.SaveLabVersionWithIngredients(version, copiedIngredients);

            return RedirectToAction("Lab", new { id = version.RecipeLabEntryId });
        }


    }

}
