using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using LittleShop.Services;
using LittleShop.DTOs;

namespace LittleShop.Areas.Admin.Controllers;

[Area("Admin")]
[Authorize(Policy = "AdminOnly")]
public class ProductsController : Controller
{
    private readonly IProductService _productService;
    private readonly ICategoryService _categoryService;

    public ProductsController(IProductService productService, ICategoryService categoryService)
    {
        _productService = productService;
        _categoryService = categoryService;
    }

    public async Task<IActionResult> Index()
    {
        // Prevent caching of products list to show real-time data
        Response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
        Response.Headers.Add("Pragma", "no-cache");
        Response.Headers.Add("Expires", "0");
        
        var products = await _productService.GetAllProductsAsync();
        return View(products);
    }

    public async Task<IActionResult> Create()
    {
        var categories = await _categoryService.GetAllCategoriesAsync();
        ViewData["Categories"] = categories.Where(c => c.IsActive);
        return View(new CreateProductDto());
    }

    [HttpPost]
    public async Task<IActionResult> Create(CreateProductDto model)
    {
        Console.WriteLine($"Received Product: Name='{model?.Name}', Description='{model?.Description}', Price={model?.Price}, Stock={model?.StockQuantity}");
        Console.WriteLine($"CategoryId: {model?.CategoryId}");
        Console.WriteLine($"Weight: {model?.Weight}, WeightUnit: {model?.WeightUnit}");
        Console.WriteLine($"ModelState.IsValid: {ModelState.IsValid}");
        
        // Remove Description validation errors since it's optional
        ModelState.Remove("Description");
        
        if (!ModelState.IsValid)
        {
            Console.WriteLine("Validation errors:");
            foreach (var error in ModelState)
            {
                if (error.Value?.Errors.Count > 0)
                {
                    Console.WriteLine($"  {error.Key}: {string.Join(", ", error.Value.Errors.Select(e => e.ErrorMessage))}");
                }
            }
            
            var categories = await _categoryService.GetAllCategoriesAsync();
            ViewData["Categories"] = categories.Where(c => c.IsActive);
            return View(model);
        }

        var createdProduct = await _productService.CreateProductAsync(model);
        return RedirectToAction(nameof(Index));
    }

    public async Task<IActionResult> Edit(Guid id)
    {
        var product = await _productService.GetProductByIdAsync(id);
        if (product == null)
        {
            return NotFound();
        }

        var categories = await _categoryService.GetAllCategoriesAsync();
        ViewData["Categories"] = categories.Where(c => c.IsActive);
        ViewData["ProductId"] = id;
        ViewData["ProductPhotos"] = product.Photos;

        var model = new UpdateProductDto
        {
            Name = product.Name,
            Description = product.Description,
            WeightUnit = product.WeightUnit,
            Weight = product.Weight,
            Price = product.Price,
            StockQuantity = product.StockQuantity,
            CategoryId = product.CategoryId,
            IsActive = product.IsActive
        };

        return View(model);
    }

    [HttpPost]
    public async Task<IActionResult> Edit(Guid id, UpdateProductDto model)
    {
        if (!ModelState.IsValid)
        {
            var categories = await _categoryService.GetAllCategoriesAsync();
            ViewData["Categories"] = categories.Where(c => c.IsActive);
            ViewData["ProductId"] = id;
            return View(model);
        }

        var success = await _productService.UpdateProductAsync(id, model);
        if (!success)
        {
            return NotFound();
        }

        return RedirectToAction(nameof(Index));
    }

    [HttpPost]
    public async Task<IActionResult> UploadPhoto(Guid id, IFormFile file, string? altText)
    {
        if (file != null && file.Length > 0)
        {
            await _productService.AddProductPhotoAsync(id, file, altText);
        }

        return RedirectToAction(nameof(Edit), new { id });
    }

    [HttpPost]
    public async Task<IActionResult> DeletePhoto(Guid id, Guid photoId)
    {
        await _productService.RemoveProductPhotoAsync(id, photoId);
        return RedirectToAction(nameof(Edit), new { id });
    }

    [HttpPost]
    public async Task<IActionResult> Delete(Guid id)
    {
        await _productService.DeleteProductAsync(id);
        return RedirectToAction(nameof(Index));
    }
}