using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebVentaCoche.DataBase;
using WebVentaCoche.Helpers;
using WebVentaCoche.Models;
using System.Linq;
using System.Security.Claims;
using WebVentaCoche.Enums;

namespace WebVentaCoche.Controllers
{
    public class CartController : Controller
    {
        private readonly ApplicationDbContext _context;

        public CartController(ApplicationDbContext context)
        {
            _context = context;
        }

        //GET:/Cart/Index
        public IActionResult Index()
        {
            // Diccionario de IDs -> Cantidades desde sesión (o cualquier fuente)
            var itemsDict = CartSessionHelper.GetCartItems(HttpContext.Session);

            // Crear tu ViewModel
            var viewModel = new CartViewModel();

            foreach (var kvp in itemsDict)
            {
                var productId = kvp.Key;
                var amount = kvp.Value;
                var product = _context.Products.Find(productId);

                if (product != null)
                {
                    viewModel.Products.Add(new CartProduct
                    {
                        Product = product,
                        Amount = amount
                    });
                }
            }

            return View(viewModel);
        }

        // POST: /Cart/Purchase
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Purchase()
        {
            // 1) Obtén el carrito de la sesión
            var items = CartSessionHelper.GetCartItems(HttpContext.Session);
            if (!items.Any())
            {
                TempData["Error"] = "El carrito está vacío.";
                return RedirectToAction("Index");
            }

            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier)!;

            var addr = await _context.Addresses.Where(a => a.UserId == userId).FirstOrDefaultAsync();
            if (addr == null)
            {
                TempData["Error"] = "No tienes ninguna dirección guardada. Primero añade una dirección en tu perfil.";
                return RedirectToAction("Addresses", "Account");
            }
            var shippingAddress = $"{addr.Street}, {addr.City}, {addr.State}, {addr.ZipCode}, {addr.Country}";

            var order = new Order
            {
                UserId = userId,
                OrderDate = DateTime.UtcNow,
                Status = OrderStatus.Pending,
                ShippingAddress = shippingAddress
            };

            decimal total = 0m;
            foreach (var (productId, quantity) in items)
            {
                var product = await _context.Products.FindAsync(productId);
                if (product == null) continue;

                var detail = new OrderDetail
                {
                    ProductId = product.Id,
                    Quantity = quantity,
                    UnitPrice = product.Price
                };
                total += detail.Subtotal;
                order.OrderDetails.Add(detail);
            }

            order.TotalAmount = total;
            _context.Orders.Add(order);
            await _context.SaveChangesAsync();

            CartSessionHelper.ClearCart(HttpContext.Session);

            return RedirectToAction("Details", "Order", new { id = order.Id });
        }

        //POST:/Cart/AddProductToCart
        [HttpPost]
        public IActionResult AddProductToCart(int id)
        {
            var product = _context.Products.Find(id);
            if (product == null)
            {
                return NotFound();
            }

            // Añade a la sesión
            CartSessionHelper.AddToCart(HttpContext.Session, id);

            // Devuelve la cuenta actualizada para actualizar el badge
            var productIds = CartSessionHelper.GetCartItems(HttpContext.Session);
            int count = productIds.Count;

            return Json(new { success = true, cartCount = count });
        }

        //POST:/Cart/Remove
        [HttpPost]
        public IActionResult Remove(int id)
        {
            CartSessionHelper.RemoveFromCart(HttpContext.Session, id);
            return RedirectToAction("Index");
        }

        //POST:/Cart/Clear
        [HttpPost]
        public IActionResult Clear()
        {
            CartSessionHelper.ClearCart(HttpContext.Session);
            return RedirectToAction("Index");
        }

        //GET:/Cart/Checkout
        public IActionResult Checkout()
        {
            return View();
        }
    }
}
