using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Aberwyn.Models;
using Aberwyn.Data;
using System;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Aberwyn.Controllers
{
    public class FoodMenuController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly IHostEnvironment _env;

        public FoodMenuController(IConfiguration configuration, IHostEnvironment env)
        {
            _configuration = configuration;
            _env = env;
        }

        public IActionResult Veckomeny(int? week, int? year)
        {
            var menuService = new MenuService(_configuration, _env);

            var today = DateTime.Today;
            int resolvedWeek = week ?? ISOWeek.GetWeekOfYear(today);
            int resolvedYear = year ?? today.Year;

            var menus = menuService.GetWeeklyMenu(resolvedWeek, resolvedYear);

            var vm = new WeeklyMenuViewModel
            {
                WeekNumber = resolvedWeek,
                Year = resolvedYear,
                WeeklyMenus = menus,
                AvailableCooks = menuService.GetUsers()
            };

            var recent = menuService
                .GetMenuEntriesByDateRange(DateTime.Now.AddDays(-28), DateTime.Now)
                .Select(x => new WeeklyMenuViewModel.RecentMenuEntry
                {
                    Date = x.Date,
                    BreakfastMealName = x.BreakfastMealName,
                    LunchMealName = x.LunchMealName,
                    DinnerMealName = x.DinnerMealName
                })
                .ToList();

            vm.RecentEntries = recent;
            ViewBag.AvailableMeals = menuService.GetMeals();

            return View(vm);
        }

        [HttpPost]
        public IActionResult AddMealAjax([FromBody] Meal meal)
        {
            if (meal == null || string.IsNullOrWhiteSpace(meal.Name))
                return BadRequest("Ogiltigt måltidsobjekt.");

            var service = new MenuService(_configuration, _env);

            // Kontrollera om en måltid med samma namn redan finns
            var existing = service.GetMeals()
                .FirstOrDefault(m => m.Name.Equals(meal.Name, StringComparison.OrdinalIgnoreCase));

            if (existing == null)
            {
                // Fyll i CreatedAt om det inte sätts automatiskt i databasen
                meal.CreatedAt = DateTime.Now;
                service.SaveOrUpdateMeal(meal);
                existing = meal;
            }
            else
            {
                // Om måltiden finns men saknar data (t.ex. är bara ett namn) kan vi uppdatera den
                existing.Description = meal.Description;
                existing.ProteinType = meal.ProteinType;
                existing.CarbType = meal.CarbType;
                existing.RecipeUrl = meal.RecipeUrl;
                existing.ImageUrl = meal.ImageUrl;
                service.SaveOrUpdateMeal(existing);
            }

            return Json(new
            {
                Id = existing.Id,
                Name = existing.Name,
                Description = existing.Description,
                ProteinType = existing.ProteinType,
                CarbType = existing.CarbType,
                RecipeUrl = existing.RecipeUrl
            });
        }

        public IActionResult MealAdmin()
        {
            var service = new MenuService(_configuration, _env);
            var meals = service.GetMealsDetailed();
            return View("MealAdmin", meals);
        }

        [HttpGet]
        public JsonResult SearchMeals(string term)
        {
            if (string.IsNullOrWhiteSpace(term))
                return Json(new List<string>());

            var menuService = new MenuService(_configuration, _env);
            var meals = menuService.GetMeals();

            var result = meals
                .Where(m => m.Name != null && m.Name.Contains(term, StringComparison.OrdinalIgnoreCase))
                .Select(m => m.Name)
                .Distinct()
                .Take(10)
                .ToList();

            return Json(result);
        }

        [HttpPost]
        public IActionResult SaveVeckomeny(IFormCollection form, int week, int year)
        {
            var menuService = new MenuService(_configuration, _env);
            var allMeals = menuService.GetMeals();

            var model = new MenuViewModel
            {
                WeekNumber = week,
                Year = year,
                WeeklyMenus = new List<WeeklyMenu>()
            };

            var entriesByDay = new Dictionary<int, WeeklyMenu>();

            foreach (var key in form.Keys.Where(k => k.StartsWith("Meal[", StringComparison.OrdinalIgnoreCase)))
            {
                var match = Regex.Match(key, @"Meal\[(\d+)\]\[(\w+)\]");
                if (!match.Success) continue;

                int day = int.Parse(match.Groups[1].Value);
                string mealType = match.Groups[2].Value;
                string mealName = form[key];
                string cook = form[$"Cook[{day}]"];

                if (!entriesByDay.TryGetValue(day, out var entry))
                {
                    entry = new WeeklyMenu
                    {
                        WeekNumber = week,
                        Year = year,
                        DayOfWeek = day + 1
                    };
                    entriesByDay[day] = entry;
                }

                entry.Cook = cook;

                if (string.IsNullOrWhiteSpace(mealName))
                {
                    switch (mealType.ToLower())
                    {
                        case "lunch":
                            entry.LunchMealId = null;
                            entry.LunchMealName = null;
                            break;
                        case "middag":
                            entry.DinnerMealId = null;
                            entry.DinnerMealName = null;
                            break;
                        case "frukost":
                            entry.BreakfastMealId = null;
                            entry.BreakfastMealName = null;
                            break;
                    }
                    continue;
                }

                var meal = allMeals.FirstOrDefault(m => m.Name.Equals(mealName, StringComparison.OrdinalIgnoreCase))
                           ?? new Meal { Name = mealName };

                if (meal.Id == 0)
                    menuService.SaveOrUpdateMeal(meal);

                switch (mealType.ToLower())
                {
                    case "lunch":
                        entry.LunchMealId = meal.Id;
                        entry.LunchMealName = meal.Name;
                        break;
                    case "middag":
                        entry.DinnerMealId = meal.Id;
                        entry.DinnerMealName = meal.Name;
                        break;
                    case "frukost":
                        entry.BreakfastMealId = meal.Id;
                        entry.BreakfastMealName = meal.Name;
                        break;
                }
            }

            model.WeeklyMenus = entriesByDay.Values.ToList();
            menuService.UpdateWeeklyMenu(model);

            return RedirectToAction("Veckomeny", new { week, year });
        }


    }
}
