using Microsoft.AspNetCore.Mvc;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers
{
    public class ShopController : Controller
    {
        private readonly MongoDBService _mongoService;
        private readonly string _productsCollection = "Products";

        public ShopController(MongoDBService mongoService)
        {
            _mongoService = mongoService;
        }

        public async Task<IActionResult> Index(string? category, string? sort)
        {
            var products = await _mongoService.GetAllAsync<Product>(_productsCollection);
            var activeProducts = products.Where(p => p.IsActive).ToList();

            // Filter by category if specified
            if (!string.IsNullOrEmpty(category) && category != "all")
            {
                activeProducts = activeProducts.Where(p => p.Category == category).ToList();
            }

            // Sort products
            activeProducts = sort switch
            {
                "price-low" => activeProducts.OrderBy(p => p.Price).ToList(),
                "price-high" => activeProducts.OrderByDescending(p => p.Price).ToList(),
                "newest" => activeProducts.OrderByDescending(p => p.CreatedAt).ToList(),
                _ => activeProducts.OrderByDescending(p => p.IsFeatured).ToList()
            };

            ViewBag.SelectedCategory = category ?? "all";
            ViewBag.SelectedSort = sort ?? "featured";
            ViewBag.Categories = activeProducts.Select(p => p.Category).Distinct().ToList();

            return View(activeProducts);
        }

        public async Task<IActionResult> Product(string id)
        {
            var product = await _mongoService.GetByIdAsync<Product>(_productsCollection, id);

            if (product == null)
            {
                return NotFound();
            }

            // Debug logging
            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"}");

            // Track product view
            var sessionId = HttpContext.Session.Id;
            var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
            var productView = new ProductView
            {
                ProductId = id,
                SessionId = sessionId,
                IpAddress = ipAddress,
                ViewedAt = DateTime.UtcNow
            };
            await _mongoService.InsertAsync("ProductViews", productView);

            // Get related products based on:
            // 1. Same category
            // 2. Most viewed products
            // 3. Exclude current product
            var allProducts = await _mongoService.GetAllAsync<Product>(_productsCollection);
            var allViews = await _mongoService.GetAllAsync<ProductView>("ProductViews");

            // Count views for each product
            var productViewCounts = allViews
                .GroupBy(v => v.ProductId)
                .ToDictionary(g => g.Key, g => g.Count());

            var relatedProducts = allProducts
                .Where(p => p.IsActive && p.Id != id)
                .OrderByDescending(p =>
                    (p.Category == product.Category ? 100 : 0) + // Same category bonus
                    (productViewCounts.ContainsKey(p.Id ?? "") ? productViewCounts[p.Id ?? ""] : 0) + // View count
                    (p.IsFeatured ? 50 : 0) + // Featured bonus
                    (p.UnitsSold * 2) // Sales popularity
                )
                .Take(4)
                .ToList();

            ViewBag.RelatedProducts = relatedProducts;
            return View(product);
        }
    }
}
