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

namespace SkyArtShop.Controllers
{
    [Route("admin/products")]
    [Authorize(Roles = "Admin")]
    public class AdminProductsController : Controller
    {
        private readonly MongoDBService _mongoService;
        private readonly SlugService _slugService;
        private readonly string _productsCollection = "Products";

        public AdminProductsController(MongoDBService mongoService, SlugService slugService)
        {
            _mongoService = mongoService;
            _slugService = slugService;
        }

        [HttpGet("")]
        public async Task<IActionResult> Index()
        {
            var products = await _mongoService.GetAllAsync<Product>(_productsCollection);
            return View(products.OrderByDescending(p => p.CreatedAt).ToList());
        }

        [HttpGet("create")]
        public IActionResult Create() => View(new Product());

        [HttpPost("create")]
        public async Task<IActionResult> Create(Product product)
        {
            // Remove validation errors for optional fields
            ModelState.Remove("ShortDescription");
            ModelState.Remove("Description");

            if (!ModelState.IsValid)
            {
                return View(product);
            }

            // Ensure checkbox defaults when unchecked
            if (!Request.Form.ContainsKey("IsActive")) product.IsActive = false;
            if (!Request.Form.ContainsKey("IsFeatured")) product.IsFeatured = false;
            if (!Request.Form.ContainsKey("IsTopSeller")) product.IsTopSeller = false;

            // Handle multiple colors from form
            var colors = Request.Form["Colors"].Where(c => !string.IsNullOrEmpty(c)).Select(c => c!).ToList();
            product.Colors = colors.Any() ? colors : new List<string>();

            // Debug logging
            Console.WriteLine($"[CREATE] Colors received: {colors.Count}");
            if (colors.Any())
            {
                Console.WriteLine($"[CREATE] Colors: {string.Join(", ", colors)}");
            }

            product.CreatedAt = DateTime.UtcNow;
            product.UpdatedAt = DateTime.UtcNow;
            product.Slug = _slugService.GenerateSlug(product.Name);
            await _mongoService.InsertAsync(_productsCollection, product);
            TempData["SuccessMessage"] = "Product created successfully!";
            return RedirectToAction("Index");
        }

        [HttpGet("edit/{id}")]
        public async Task<IActionResult> Edit(string id)
        {
            var product = await _mongoService.GetByIdAsync<Product>(_productsCollection, id);
            if (product == null) return NotFound();
            return View("Create", product);
        }

        [HttpPost("edit/{id}")]
        public async Task<IActionResult> Edit(string id, Product product)
        {
            // Remove validation errors for optional fields
            ModelState.Remove("Images");
            ModelState.Remove("Slug");
            ModelState.Remove("ShortDescription");
            ModelState.Remove("Description");

            if (!ModelState.IsValid)
            {
                return View("Create", product);
            }

            // Ensure checkbox defaults when unchecked
            if (!Request.Form.ContainsKey("IsActive")) product.IsActive = false;
            if (!Request.Form.ContainsKey("IsFeatured")) product.IsFeatured = false;
            if (!Request.Form.ContainsKey("IsTopSeller")) product.IsTopSeller = false;

            // Get existing product to preserve data
            var existingProduct = await _mongoService.GetByIdAsync<Product>(_productsCollection, id);
            if (existingProduct == null)
            {
                TempData["ErrorMessage"] = "Product not found.";
                return RedirectToAction("Index");
            }

            // Update editable fields
            existingProduct.Name = product.Name;
            existingProduct.ShortDescription = product.ShortDescription;
            existingProduct.Description = product.Description;
            existingProduct.Price = product.Price;
            existingProduct.Category = product.Category;
            existingProduct.Color = product.Color;

            // Handle multiple colors from form
            var colors = Request.Form["Colors"].Where(c => !string.IsNullOrEmpty(c)).Select(c => c!).ToList();
            existingProduct.Colors = colors.Any() ? colors : new List<string>();

            // Debug logging
            Console.WriteLine($"[EDIT] Colors received: {colors.Count}");
            if (colors.Any())
            {
                Console.WriteLine($"[EDIT] Colors: {string.Join(", ", colors)}");
            }
            Console.WriteLine($"[EDIT] Product Colors property: {existingProduct.Colors?.Count ?? 0}");

            existingProduct.StockQuantity = product.StockQuantity;
            existingProduct.IsFeatured = product.IsFeatured;
            existingProduct.IsTopSeller = product.IsTopSeller;
            existingProduct.IsActive = product.IsActive;
            existingProduct.UpdatedAt = DateTime.UtcNow;
            existingProduct.Slug = _slugService.GenerateSlug(product.Name);

            // Update images
            if (Request.Form.ContainsKey("Images"))
            {
                var images = Request.Form["Images"].Where(img => !string.IsNullOrEmpty(img)).Select(img => img!).ToList();
                existingProduct.Images = images;

                // Set first image as main ImageUrl if not explicitly set
                if (images.Any() && string.IsNullOrEmpty(product.ImageUrl))
                {
                    existingProduct.ImageUrl = images[0] ?? "";
                }
            }

            // Preserve or update ImageUrl
            if (!string.IsNullOrEmpty(product.ImageUrl))
            {
                existingProduct.ImageUrl = product.ImageUrl;
            }

            // Update SKU and CostPrice if provided
            if (!string.IsNullOrEmpty(product.SKU))
            {
                existingProduct.SKU = product.SKU;
            }
            if (product.CostPrice > 0)
            {
                existingProduct.CostPrice = product.CostPrice;
            }

            await _mongoService.UpdateAsync(_productsCollection, id, existingProduct);
            TempData["SuccessMessage"] = "Product updated successfully!";
            return RedirectToAction("Index");
        }

        [HttpPost("delete/{id}")]
        public async Task<IActionResult> Delete(string id)
        {
            await _mongoService.DeleteAsync<Product>(_productsCollection, id);
            TempData["SuccessMessage"] = "Product deleted successfully!";
            return RedirectToAction("Index");
        }
    }
}
