using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using turf_tasker.Data;
using turf_tasker.Models;

namespace turf_tasker.Controllers
{
    public class LawnCareEventsController : Controller
    {
        private readonly ApplicationDbContext _context;

        public LawnCareEventsController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> Index(string sortOrder, string searchString)
        {
            ViewData["DateSortParm"] = String.IsNullOrEmpty(sortOrder) ? "date_desc" : "";
            ViewData["TypeSortParm"] = sortOrder == "Type" ? "type_desc" : "Type";
            ViewData["CurrentFilter"] = searchString;

            var events = from e in _context.LawnCareEvents
                select e;

            if (!String.IsNullOrEmpty(searchString))
            {
                events = events.Where(e => 
                    e.Notes!.Contains(searchString) || 
                    e.EventType.ToString().Contains(searchString)
                );
            }

            switch (sortOrder)
            {
                case "date_desc":
                    events = events.OrderByDescending(e => e.EventDate);
                    break;
                case "Type":
                    events = events.OrderBy(e => e.EventType);
                    break;
                case "type_desc":
                    events = events.OrderByDescending(e => e.EventType);
                    break;
                default: // Default sort order is by date, ascending
                    events = events.OrderBy(e => e.EventDate);
                    break;
            }
            return View(await events.AsNoTracking().ToListAsync());
        }

        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var lawnCareEvent = await _context.LawnCareEvents
                .FirstOrDefaultAsync(m => m.Id == id);
            if (lawnCareEvent == null)
            {
                return NotFound();
            }

            return View(lawnCareEvent);
        }

        
        public IActionResult Create()
        {
            var model = new LawnCareEvent { EventDate = DateTime.Now };
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,EventType,EventDate,MowingPattern,Notes")] LawnCareEvent lawnCareEvent)
        {
            if (ModelState.IsValid)
            {
                _context.Add(lawnCareEvent);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(lawnCareEvent);
        }
        
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var lawnCareEvent = await _context.LawnCareEvents.FindAsync(id);
            if (lawnCareEvent == null)
            {
                return NotFound();
            }
            return View(lawnCareEvent);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,EventType,EventDate,MowingPattern,Notes")] LawnCareEvent lawnCareEvent)
        {
            if (id != lawnCareEvent.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(lawnCareEvent);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LawnCareEventExists(lawnCareEvent.Id)) // This uses the private method below
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(lawnCareEvent);
        }

        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var lawnCareEvent = await _context.LawnCareEvents
                .FirstOrDefaultAsync(m => m.Id == id);
            if (lawnCareEvent == null)
            {
                return NotFound();
            }

            return View(lawnCareEvent);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var lawnCareEvent = await _context.LawnCareEvents.FindAsync(id);
            if (lawnCareEvent != null)
            {
                _context.LawnCareEvents.Remove(lawnCareEvent);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool LawnCareEventExists(int id)
        {
            return _context.LawnCareEvents.Any(e => e.Id == id);
        }

        public IActionResult Calendar()
        {
            return View();
        }
        
        [HttpGet]
        public async Task<JsonResult> GetEventsJson()
        {
            var events = await _context.LawnCareEvents.AsNoTracking().ToListAsync();

            var calendarEvents = events.Select(e => new
            {
                id = e.Id,
                title = $"{e.EventType} {((e.EventType == LawnCareEventType.Mowing && e.MowingPattern.HasValue) ? $"({e.MowingPattern})" : "")}",
                start = e.EventDate.ToString("yyyy-MM-dd"),
                allDay = true,
                url = $"/LawnCareEvents/Details/{e.Id}",
                color = e.EventType switch
                {
                    LawnCareEventType.Mowing => "#28a745",
                    LawnCareEventType.Watering => "#007bff",
                    LawnCareEventType.Fertilizing => "#ffc107",
                    LawnCareEventType.Aeration => "#6f42c1",
                    LawnCareEventType.WeedControl => "#dc3545",
                    _ => "#6c757d"
                }
            }).ToList();

            return Json(calendarEvents);
        }
    }
}