using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace SkyArtShop.Controllers;

[Route("admin/upload")]
[Authorize(Roles = "Admin,MasterAdmin")]
[IgnoreAntiforgeryToken]
public class AdminUploadController : Controller
{
	private readonly IWebHostEnvironment _environment;

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

	[HttpGet("")]
	public IActionResult Index()
	{
		string path = Path.Combine(_environment.WebRootPath, "uploads", "images");
		List<string> model = new List<string>();
		if (Directory.Exists(path))
		{
			List<string> list = (from f in Directory.GetFiles(path)
				select "/uploads/images/" + Path.GetFileName(f) into f
				orderby f descending
				select f).ToList();
			model = list;
		}
		return View(model);
	}

	[HttpPost("image")]
	public async Task<IActionResult> UploadImage(IFormFile file)
	{
		if (file == null || file.Length == 0L)
		{
			return Json(new
			{
				success = false,
				message = "No file uploaded"
			});
		}
		string[] source = new string[5] { ".jpg", ".jpeg", ".png", ".gif", ".webp" };
		string value = Path.GetExtension(file.FileName).ToLowerInvariant();
		if (!source.Contains(value))
		{
			return Json(new
			{
				success = false,
				message = "Invalid file type"
			});
		}
		try
		{
			string text = Path.Combine(_environment.WebRootPath, "uploads", "images");
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
			}
			string fileName = $"{Guid.NewGuid()}{value}";
			string path = Path.Combine(text, fileName);
			using FileStream stream = new FileStream(path, 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)
	{
		List<string> uploadedUrls = new List<string>();
		foreach (IFormFile file in files)
		{
			if (file == null || file.Length == 0L)
			{
				continue;
			}
			string value = Path.GetExtension(file.FileName).ToLowerInvariant();
			string[] source = new string[5] { ".jpg", ".jpeg", ".png", ".gif", ".webp" };
			if (source.Contains(value))
			{
				string text = Path.Combine(_environment.WebRootPath, "uploads", "images");
				if (!Directory.Exists(text))
				{
					Directory.CreateDirectory(text);
				}
				string fileName = $"{Guid.NewGuid()}{value}";
				string path = Path.Combine(text, fileName);
				using FileStream stream = new FileStream(path, 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
		{
			string fileName = Path.GetFileName(imageUrl);
			string path = Path.Combine(_environment.WebRootPath, "uploads", "images", fileName);
			if (System.IO.File.Exists(path))
			{
				System.IO.File.Delete(path);
				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
			});
		}
	}

	[HttpGet("list")]
	public IActionResult ListImages()
	{
		string uploadsPath = Path.Combine(_environment.WebRootPath, "uploads", "images");
		List<string> data = new List<string>();
		if (Directory.Exists(uploadsPath))
		{
			List<string> list = (from f in Directory.GetFiles(uploadsPath)
				select "/uploads/images/" + Path.GetFileName(f) into f
				orderby System.IO.File.GetCreationTime(Path.Combine(uploadsPath, Path.GetFileName(f))) descending
				select f).ToList();
			data = list;
		}
		return Json(data);
	}

	[HttpPost("create-folder")]
	public IActionResult CreateFolder([FromBody] string folderName)
	{
		try
		{
			if (string.IsNullOrWhiteSpace(folderName))
			{
				return Json(new
				{
					success = false,
					message = "Folder name cannot be empty"
				});
			}
			string text = string.Join("_", folderName.Split(Path.GetInvalidFileNameChars()));
			string path = Path.Combine(_environment.WebRootPath, "uploads", "images", text);
			if (Directory.Exists(path))
			{
				return Json(new
				{
					success = false,
					message = "Folder already exists"
				});
			}
			Directory.CreateDirectory(path);
			return Json(new
			{
				success = true,
				folderName = text
			});
		}
		catch (Exception ex)
		{
			return Json(new
			{
				success = false,
				message = ex.Message
			});
		}
	}

	[HttpPost("delete-folder")]
	public IActionResult DeleteFolder([FromBody] string folderPath)
	{
		try
		{
			string path = Path.Combine(_environment.WebRootPath, "uploads", "images", folderPath);
			if (!Directory.Exists(path))
			{
				return Json(new
				{
					success = false,
					message = "Folder not found"
				});
			}
			Directory.Delete(path, recursive: true);
			return Json(new
			{
				success = true
			});
		}
		catch (Exception ex)
		{
			return Json(new
			{
				success = false,
				message = ex.Message
			});
		}
	}

	[HttpGet("list-folders")]
	public IActionResult ListFolders()
	{
		try
		{
			string path = Path.Combine(_environment.WebRootPath, "uploads", "images");
			List<object> data = new List<object>();
			if (Directory.Exists(path))
			{
				var source = (from d in Directory.GetDirectories(path)
					select new
					{
						name = Path.GetFileName(d),
						path = Path.GetFileName(d),
						fileCount = Directory.GetFiles(d).Length
					}).ToList();
				data = source.Cast<object>().ToList();
			}
			return Json(data);
		}
		catch (Exception ex)
		{
			return Json(new
			{
				success = false,
				message = ex.Message
			});
		}
	}
}
