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;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers;

[Route("admin/homepage")]
[Authorize(Roles = "Admin,MasterAdmin")]
public class AdminHomepageController : Controller
{
	private readonly PostgreSQLService _pgService;

	private readonly IWebHostEnvironment _environment;

	private readonly string _sectionsCollection = "HomepageSections";

	private readonly string _settingsCollection = "SiteSettings";

	public AdminHomepageController(PostgreSQLService pgService, IWebHostEnvironment environment)
	{
		_pgService = pgService;
		_environment = environment;
	}

	[HttpGet("")]
	public async Task<IActionResult> Index()
	{
		List<HomepageSection> sections = (await _pgService.GetAllAsync<HomepageSection>(_sectionsCollection)).OrderBy((HomepageSection s) => s.DisplayOrder).ToList();
		SiteSettings siteSettings = (await _pgService.GetAllAsync<SiteSettings>(_settingsCollection)).FirstOrDefault() ?? new SiteSettings();
		base.ViewBag.Settings = siteSettings;
		return View(sections);
	}

	[HttpGet("section/{id}")]
	public async Task<IActionResult> EditSection(string id)
	{
		HomepageSection homepageSection = await _pgService.GetByIdAsync<HomepageSection>(_sectionsCollection, id);
		if (homepageSection == null)
		{
			base.TempData["ErrorMessage"] = "Section not found.";
			return RedirectToAction("Index");
		}
		return View(homepageSection);
	}

	[HttpPost("section/update")]
	public async Task<IActionResult> UpdateSection(HomepageSection section, IFormFile? imageFile, string? SelectedImageUrl)
	{
		base.ModelState.Remove("Content");
		base.ModelState.Remove("AdditionalData");
		base.ModelState.Remove("SelectedImageUrl");
		if (!base.ModelState.IsValid)
		{
			foreach (ModelError item in base.ModelState.Values.SelectMany((ModelStateEntry v) => v.Errors))
			{
				Console.WriteLine("ModelState Error: " + item.ErrorMessage);
			}
			return View("EditSection", section);
		}
		Console.WriteLine("Updating section with ID: " + section.Id);
		Console.WriteLine("Title: " + section.Title);
		Console.WriteLine("Subtitle: " + section.Subtitle);
		Console.WriteLine($"Content length: {section.Content?.Length ?? 0}");
		Console.WriteLine($"IsActive: {section.IsActive}");
		HomepageSection existingSection = await _pgService.GetByIdAsync<HomepageSection>(_sectionsCollection, section.Id);
		if (existingSection == null)
		{
			Console.WriteLine("ERROR: Section with ID " + section.Id + " not found!");
			base.TempData["ErrorMessage"] = "Section not found.";
			return RedirectToAction("Index");
		}
		Console.WriteLine("Found existing section: " + existingSection.Title);
		existingSection.SectionType = section.SectionType;
		existingSection.Title = section.Title ?? string.Empty;
		existingSection.Subtitle = section.Subtitle ?? string.Empty;
		existingSection.Content = section.Content ?? string.Empty;
		existingSection.ButtonText = section.ButtonText ?? string.Empty;
		existingSection.ButtonUrl = section.ButtonUrl ?? string.Empty;
		existingSection.IsActive = section.IsActive;
		existingSection.UpdatedAt = DateTime.UtcNow;
		if (existingSection.AdditionalData == null)
		{
			existingSection.AdditionalData = new Dictionary<string, string>();
		}
		if (!string.IsNullOrEmpty(SelectedImageUrl))
		{
			existingSection.ImageUrl = SelectedImageUrl;
			Console.WriteLine("Image selected from library: " + existingSection.ImageUrl);
		}
		else if (imageFile != null && imageFile.Length > 0)
		{
			string text = Path.Combine(_environment.WebRootPath, "uploads", "images");
			Directory.CreateDirectory(text);
			string uniqueFileName = $"{Guid.NewGuid()}_{imageFile.FileName}";
			string path = Path.Combine(text, uniqueFileName);
			using (FileStream fileStream = new FileStream(path, FileMode.Create))
			{
				await imageFile.CopyToAsync(fileStream);
			}
			existingSection.ImageUrl = "/uploads/images/" + uniqueFileName;
			Console.WriteLine("New image uploaded: " + existingSection.ImageUrl);
		}
		await _pgService.UpdateAsync(_sectionsCollection, existingSection.Id, existingSection);
		Console.WriteLine("Section updated successfully in database");
		base.TempData["SuccessMessage"] = "Section updated successfully!";
		return RedirectToAction("Index");
	}

	[HttpGet("section/create")]
	public IActionResult CreateSection()
	{
		return View();
	}

	[HttpPost("section/create")]
	public async Task<IActionResult> CreateSection(HomepageSection section, IFormFile? imageFile, string? SelectedImageUrl)
	{
		base.ModelState.Remove("Content");
		base.ModelState.Remove("AdditionalData");
		if (!base.ModelState.IsValid)
		{
			return View(section);
		}
		if (!string.IsNullOrEmpty(SelectedImageUrl))
		{
			section.ImageUrl = SelectedImageUrl;
			Console.WriteLine("Image selected from library: " + section.ImageUrl);
		}
		else if (imageFile != null && imageFile.Length > 0)
		{
			string text = Path.Combine(_environment.WebRootPath, "uploads", "images");
			Directory.CreateDirectory(text);
			string uniqueFileName = $"{Guid.NewGuid()}_{imageFile.FileName}";
			string path = Path.Combine(text, uniqueFileName);
			using (FileStream fileStream = new FileStream(path, FileMode.Create))
			{
				await imageFile.CopyToAsync(fileStream);
			}
			section.ImageUrl = "/uploads/images/" + uniqueFileName;
		}
		if (section.AdditionalData == null)
		{
			section.AdditionalData = new Dictionary<string, string>();
		}
		List<HomepageSection> source = await _pgService.GetAllAsync<HomepageSection>(_sectionsCollection);
		section.DisplayOrder = (source.Any() ? (source.Max((HomepageSection s) => s.DisplayOrder) + 1) : 0);
		section.CreatedAt = DateTime.UtcNow;
		section.UpdatedAt = DateTime.UtcNow;
		await _pgService.InsertAsync(_sectionsCollection, section);
		base.TempData["SuccessMessage"] = "Section created successfully!";
		return RedirectToAction("Index");
	}

	[HttpPost("section/delete/{id}")]
	public async Task<IActionResult> DeleteSection(string id)
	{
		await _pgService.DeleteAsync<HomepageSection>(_sectionsCollection, id);
		base.TempData["SuccessMessage"] = "Section deleted successfully!";
		return RedirectToAction("Index");
	}

	[HttpPost("section/reorder")]
	public async Task<IActionResult> ReorderSections([FromBody] List<string> sectionIds)
	{
		for (int i = 0; i < sectionIds.Count; i++)
		{
			HomepageSection homepageSection = await _pgService.GetByIdAsync<HomepageSection>(_sectionsCollection, sectionIds[i]);
			if (homepageSection != null)
			{
				homepageSection.DisplayOrder = i;
				homepageSection.UpdatedAt = DateTime.UtcNow;
				await _pgService.UpdateAsync(_sectionsCollection, homepageSection.Id, homepageSection);
			}
		}
		return Json(new
		{
			success = true
		});
	}

	[HttpPost("section/toggle/{id}")]
	public async Task<IActionResult> ToggleSection(string id)
	{
		HomepageSection section = await _pgService.GetByIdAsync<HomepageSection>(_sectionsCollection, id);
		if (section != null)
		{
			section.IsActive = !section.IsActive;
			section.UpdatedAt = DateTime.UtcNow;
			await _pgService.UpdateAsync(_sectionsCollection, section.Id, section);
			base.TempData["SuccessMessage"] = "Section " + (section.IsActive ? "activated" : "deactivated") + " successfully!";
		}
		return RedirectToAction("Index");
	}

	[HttpPost("footer/update")]
	public async Task<IActionResult> UpdateFooter(string footerText)
	{
		SiteSettings siteSettings = (await _pgService.GetAllAsync<SiteSettings>(_settingsCollection)).FirstOrDefault();
		if (siteSettings == null)
		{
			siteSettings = new SiteSettings
			{
				FooterText = footerText
			};
			await _pgService.InsertAsync(_settingsCollection, siteSettings);
		}
		else
		{
			siteSettings.FooterText = footerText;
			siteSettings.UpdatedAt = DateTime.UtcNow;
			await _pgService.UpdateAsync(_settingsCollection, siteSettings.Id, siteSettings);
		}
		base.TempData["SuccessMessage"] = "Footer updated successfully!";
		return RedirectToAction("Index");
	}
}
