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

namespace SkyArtShop.Controllers
{
    [Route("admin/upload")]
    [Authorize(Roles="Admin")]
    public class AdminUploadController : Controller
    {
        private readonly IWebHostEnvironment _environment;

        public AdminUploadController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        [HttpGet("")]
        public IActionResult Index()
        {
            var uploadsPath = Path.Combine(_environment.WebRootPath, "uploads", "images");
            var images = new List<string>();
            
            if (Directory.Exists(uploadsPath))
            {
                var files = Directory.GetFiles(uploadsPath)
                    .Select(f => $"/uploads/images/{Path.GetFileName(f)}")
                    .OrderByDescending(f => f)
                    .ToList();
                images = files;
            }
            
            return View(images);
        }

        [HttpPost("image")]
        public async Task<IActionResult> UploadImage(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return Json(new { success = false, message = "No file uploaded" });
            }
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".webp" };
            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (!allowedExtensions.Contains(extension))
            {
                return Json(new { success = false, message = "Invalid file type" });
            }
            try
            {
                var uploadsPath = Path.Combine(_environment.WebRootPath, "uploads", "images");
                if (!Directory.Exists(uploadsPath)) Directory.CreateDirectory(uploadsPath);
                var fileName = $"{Guid.NewGuid()}{extension}";
                var filePath = Path.Combine(uploadsPath, fileName);
                using var stream = new FileStream(filePath, FileMode.Create);
                await file.CopyToAsync(stream);
                return Json(new { success = true, url = $"/uploads/images/{fileName}" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [HttpPost("multiple")]
        public async Task<IActionResult> UploadMultiple(List<IFormFile> files)
        {
            var uploadedUrls = new List<string>();
            foreach (var file in files)
            {
                if (file == null || file.Length == 0) continue;
                var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".webp" };
                if (!allowedExtensions.Contains(extension)) continue;
                var uploadsPath = Path.Combine(_environment.WebRootPath, "uploads", "images");
                if (!Directory.Exists(uploadsPath)) Directory.CreateDirectory(uploadsPath);
                var fileName = $"{Guid.NewGuid()}{extension}";
                var filePath = Path.Combine(uploadsPath, fileName);
                using var stream = new FileStream(filePath, FileMode.Create);
                await file.CopyToAsync(stream);
                uploadedUrls.Add($"/uploads/images/{fileName}");
            }
            return Json(new { success = true, urls = uploadedUrls });
        }

        [HttpPost("delete")]
        public IActionResult DeleteImage([FromBody] string imageUrl)
        {
            try
            {
                var fileName = Path.GetFileName(imageUrl);
                var filePath = Path.Combine(_environment.WebRootPath, "uploads", "images", fileName);
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                    return Json(new { success = true });
                }
                return Json(new { success = false, message = "File not found" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
}
