using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers;

public class ShopController : Controller
{
	private readonly PostgreSQLService _pgService;

	private readonly string _productsCollection = "Products";

	public ShopController(PostgreSQLService pgService)
	{
		_pgService = pgService;
	}

	public async Task<IActionResult> Index(string? category, string? sort)
	{
		List<Product> source = (await _pgService.GetAllAsync<Product>(_productsCollection)).Where((Product p) => p.IsActive).ToList();
		if (!string.IsNullOrEmpty(category) && category != "all")
		{
			source = source.Where((Product p) => p.Category == category).ToList();
		}
		source = sort switch
		{
			"price-low" => source.OrderBy((Product p) => p.Price).ToList(), 
			"price-high" => source.OrderByDescending((Product p) => p.Price).ToList(), 
			"newest" => source.OrderByDescending((Product p) => p.CreatedAt).ToList(), 
			_ => source.OrderByDescending((Product p) => p.IsFeatured).ToList(), 
		};
		base.ViewBag.SelectedCategory = category ?? "all";
		base.ViewBag.SelectedSort = sort ?? "featured";
		base.ViewBag.Categories = source.Select((Product p) => p.Category).Distinct().ToList();
		return View(source);
	}

	public async Task<IActionResult> Product(string id)
	{
		Product product = await _pgService.GetByIdAsync<Product>(_productsCollection, id);
		if (product == null)
		{
			return NotFound();
		}
		Console.WriteLine("[SHOP] Product ID: " + id);
		Console.WriteLine("[SHOP] Product Name: " + product.Name);
		Console.WriteLine($"[SHOP] Colors Count: {product.Colors?.Count ?? 0}");
		if (product.Colors != null && product.Colors.Any())
		{
			Console.WriteLine("[SHOP] Colors: " + string.Join(", ", product.Colors));
		}
		Console.WriteLine("[SHOP] Legacy Color: " + (product.Color ?? "null"));
		_ = base.HttpContext.Session.Id;
		if (base.HttpContext.Connection.RemoteIpAddress?.ToString() == null)
		{
		}
		List<Product> source = await _pgService.GetAllAsync<Product>(_productsCollection);
		List<ProductView> source2 = new List<ProductView>();
		Dictionary<string, int> productViewCounts = (from v in source2
			group v by v.ProductId).ToDictionary((IGrouping<string, ProductView> g) => g.Key, (IGrouping<string, ProductView> g) => g.Count());
		List<Product> list = (from p in source
			where p.IsActive && p.Id != id
			orderby ((p.Category == product.Category) ? 100 : 0) + (productViewCounts.ContainsKey(p.Id ?? "") ? productViewCounts[p.Id ?? ""] : 0) + (p.IsFeatured ? 50 : 0) + p.UnitsSold * 2 descending
			select p).Take(4).ToList();
		base.ViewBag.RelatedProducts = list;
		return View(product);
	}
}
