using System.Diagnostics;
using System.Globalization;
using LEA.Data;
using LEA.Models;
using LEA.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LEA.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly AppDbContext _context;
    private readonly UserManager<ApplicationUser> _userManager;

    public HomeController(
        ILogger<HomeController> logger,
        AppDbContext context,
        UserManager<ApplicationUser> userManager)
    {
        _logger = logger;
        _context = context;
        _userManager = userManager;
    }

    public async Task<IActionResult> Index()
    {
        var viewModel = new DashboardViewModel();

        if (User.Identity?.IsAuthenticated ?? false)
        {
            var userId = _userManager.GetUserId(User);
            var user = await _userManager.GetUserAsync(User);

            var applications = await _context.Applications
                .Include(a => a.Contact)
                .Where(a => a.UserId == userId)
                .OrderByDescending(a => a.UpdatedAt)
                .ThenByDescending(a => a.AppliedOn)
                .Take(5)
                .ToListAsync();

            var statusCounts = await _context.Applications
                .Where(a => a.UserId == userId)
                .GroupBy(a => a.Status)
                .Select(group => new { group.Key, Count = group.Count() })
                .ToListAsync();

            var startOfCurrentMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
            var startDate = startOfCurrentMonth.AddMonths(-5);

            var monthlyResults = await _context.Applications
                .Where(a => a.UserId == userId && a.AppliedOn >= startDate)
                .GroupBy(a => new { a.AppliedOn.Year, a.AppliedOn.Month })
                .Select(group => new { group.Key.Year, group.Key.Month, Count = group.Count() })
                .ToListAsync();

            var germanCulture = CultureInfo.GetCultureInfo("de-DE");
            var monthlyStatistics = new List<MonthlyApplicationStat>();

            for (var offset = 0; offset < 6; offset++)
            {
                var currentMonth = startDate.AddMonths(offset);
                var match = monthlyResults.FirstOrDefault(result =>
                    result.Year == currentMonth.Year && result.Month == currentMonth.Month);

                var label = currentMonth.ToString("MMM yyyy", germanCulture);
                monthlyStatistics.Add(new MonthlyApplicationStat(label, match?.Count ?? 0));
            }

            viewModel.IsAuthenticated = true;
            viewModel.FullName = user?.FullName;
            viewModel.RecentApplications = applications;
            viewModel.TotalApplications = statusCounts.Sum(sc => sc.Count);
            viewModel.AppliedCount = statusCounts.FirstOrDefault(sc => sc.Key == ApplicationStatus.Applied)?.Count ?? 0;
            viewModel.InterviewCount = statusCounts.FirstOrDefault(sc => sc.Key == ApplicationStatus.Interview)?.Count ?? 0;
            viewModel.OfferCount = statusCounts.FirstOrDefault(sc => sc.Key == ApplicationStatus.Offer)?.Count ?? 0;
            viewModel.RejectedCount = statusCounts.FirstOrDefault(sc => sc.Key == ApplicationStatus.Rejected)?.Count ?? 0;
            viewModel.MonthlyApplications = monthlyStatistics;
        }

        return View(viewModel);
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
