using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers;

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

	private readonly SlugService _slugService;

	private readonly string _pagesCollection = "Pages";

	public AdminPagesController(PostgreSQLService pgService, SlugService slugService)
	{
		_pgService = pgService;
		_slugService = slugService;
	}

	[HttpGet("")]
	public async Task<IActionResult> Index()
	{
		return View((await _pgService.GetAllAsync<Page>(_pagesCollection)).OrderBy((Page p) => p.PageName).ToList());
	}

	[HttpGet("create")]
	public IActionResult Create()
	{
		return View(new Page());
	}

	[HttpPost("create")]
	public async Task<IActionResult> Create(Page page)
	{
		if (!base.ModelState.IsValid)
		{
			return View(page);
		}
		page.CreatedAt = DateTime.UtcNow;
		page.UpdatedAt = DateTime.UtcNow;
		page.PageSlug = _slugService.GenerateSlug(page.PageName);
		await _pgService.InsertAsync(_pagesCollection, page);
		base.TempData["SuccessMessage"] = "Page created successfully!";
		return RedirectToAction("Index");
	}

	[HttpGet("edit/{id}")]
	public async Task<IActionResult> Edit(string id)
	{
		Page page = await _pgService.GetByIdAsync<Page>(_pagesCollection, id);
		if (page == null)
		{
			return NotFound();
		}
		return View(page);
	}

	[HttpPost("edit/{id}")]
	public async Task<IActionResult> Edit(string id, [FromForm] Page page, IFormCollection form)
	{
		Console.WriteLine("[ADMIN-PAGES] === FORM SUBMISSION DEBUG ===");
		Console.WriteLine("[ADMIN-PAGES] Form Keys: " + string.Join(", ", form.Keys));
		foreach (string key in form.Keys)
		{
			if (key.StartsWith("ImageGallery") || key.StartsWith("TeamMembers"))
			{
				Console.WriteLine($"[ADMIN-PAGES] {key} = {form[key]}");
			}
		}
		if (!base.ModelState.IsValid)
		{
			Console.WriteLine("[ADMIN-PAGES] ModelState is INVALID");
			foreach (ModelError item2 in base.ModelState.Values.SelectMany((ModelStateEntry v) => v.Errors))
			{
				Console.WriteLine("[ADMIN-PAGES] Error: " + item2.ErrorMessage);
			}
			return View(page);
		}
		Page page2 = await _pgService.GetByIdAsync<Page>(_pagesCollection, id);
		if (page2 == null)
		{
			Console.WriteLine("[ADMIN-PAGES] Page not found: " + id);
			return NotFound();
		}
		page2.PageName = page.PageName;
		page2.Title = page.Title;
		page2.Subtitle = page.Subtitle;
		page2.Content = page.Content;
		page2.IsActive = page.IsActive;
		page2.UpdatedAt = DateTime.UtcNow;
		page2.PageSlug = _slugService.GenerateSlug(page.PageName);
		page2.AboutImage1 = form["AboutImage1"].ToString() ?? string.Empty;
		page2.AboutImage2 = form["AboutImage2"].ToString() ?? string.Empty;
		page2.ImageGallery = new List<string>();
		foreach (string item3 in form.Keys.Where((string k) => k.StartsWith("ImageGallery[")))
		{
			string text = form[item3].ToString();
			if (!string.IsNullOrEmpty(text))
			{
				page2.ImageGallery.Add(text);
			}
		}
		page2.TeamMembers = new List<TeamMember>();
		List<int> list = (from i in (from i in form.Keys.Where((string k) => k.StartsWith("TeamMembers[") && k.Contains("].Name")).Select(delegate(string k)
				{
					Match match = Regex.Match(k, "TeamMembers\\[(\\d+)\\]");
					return (!match.Success) ? (-1) : int.Parse(match.Groups[1].Value);
				})
				where i >= 0
				select i).Distinct()
			orderby i
			select i).ToList();
		foreach (int item4 in list)
		{
			TeamMember item = new TeamMember
			{
				Name = form[$"TeamMembers[{item4}].Name"].ToString(),
				Role = form[$"TeamMembers[{item4}].Role"].ToString(),
				Bio = form[$"TeamMembers[{item4}].Bio"].ToString(),
				PhotoUrl = form[$"TeamMembers[{item4}].PhotoUrl"].ToString()
			};
			page2.TeamMembers.Add(item);
		}
		Console.WriteLine($"[ADMIN-PAGES] Updating page: {page2.PageName} (Slug: {page2.PageSlug})");
		Console.WriteLine("[ADMIN-PAGES] Title: " + page2.Title);
		Console.WriteLine($"[ADMIN-PAGES] Content length: {page2.Content?.Length ?? 0}");
		Console.WriteLine($"[ADMIN-PAGES] Image Gallery Count: {page2.ImageGallery.Count}");
		Console.WriteLine($"[ADMIN-PAGES] Team Members Count: {page2.TeamMembers.Count}");
		if (page2.ImageGallery.Any())
		{
			Console.WriteLine("[ADMIN-PAGES] Gallery Images: " + string.Join(", ", page2.ImageGallery));
		}
		if (page2.TeamMembers.Any())
		{
			foreach (TeamMember teamMember in page2.TeamMembers)
			{
				Console.WriteLine($"[ADMIN-PAGES] Team Member: {teamMember.Name} - {teamMember.Role} - Photo: {teamMember.PhotoUrl}");
			}
		}
		await _pgService.UpdateAsync(_pagesCollection, id, page2);
		base.TempData["SuccessMessage"] = "Page updated successfully!";
		return RedirectToAction("Index");
	}

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