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;
        }

        // GET: LawnCareEvents
        public async Task<IActionResult> Index(string sortOrder, string searchString)
        {
            // Use ViewData to pass sort order info to the view
            ViewData["DateSortParm"] = String.IsNullOrEmpty(sortOrder) ? "date_desc" : "";
            ViewData["TypeSortParm"] = sortOrder == "Type" ? "type_desc" : "Type";
            ViewData["CurrentFilter"] = searchString;

            // Start with a base query that can be modified
            var events = from e in _context.LawnCareEvents
                select e;

            // Apply the filter if a search string is provided
            if (!String.IsNullOrEmpty(searchString))
            {
                events = events.Where(e => 
                    e.Notes!.Contains(searchString) || 
                    e.EventType.ToString().Contains(searchString)
                );
            }

            // Apply the sorting based on the sortOrder parameter
            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;
            }

            // Execute the query and return the view with the filtered/sorted list
            return View(await events.AsNoTracking().ToListAsync());
        }

        // GET: LawnCareEvents/Details/5
        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);
        }

        // GET: LawnCareEvents/Create
        // MODIFIED: We now create a model with a default date.
        public IActionResult Create()
        {
            var model = new LawnCareEvent { EventDate = DateTime.Now };
            return View(model);
        }

        // POST: LawnCareEvents/Create
        [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);
        }

        // GET: LawnCareEvents/Edit/5
        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);
        }

        // POST: LawnCareEvents/Edit/5
        [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))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(lawnCareEvent);
        }

        // GET: LawnCareEvents/Delete/5
        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);
        }

        // POST: LawnCareEvents/Delete/5
        [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);
        }
    }
}