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

namespace SkyArtShop.Controllers
{
    [Route("admin/pages")]
    [Authorize(Roles = "Admin")]
    public class AdminPagesController : Controller
    {
        private readonly MongoDBService _mongoService;
        private readonly SlugService _slugService;
        private readonly string _pagesCollection = "Pages";

        public AdminPagesController(MongoDBService mongoService, SlugService slugService)
        {
            _mongoService = mongoService;
            _slugService = slugService;
        }

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

        [HttpGet("create")]
        public IActionResult Create() => View(new Page());

        [HttpPost("create")]
        public async Task<IActionResult> Create(Page page)
        {
            if (!ModelState.IsValid)
            {
                return View(page);
            }

            page.CreatedAt = DateTime.UtcNow;
            page.UpdatedAt = DateTime.UtcNow;
            page.PageSlug = _slugService.GenerateSlug(page.PageName);
            await _mongoService.InsertAsync(_pagesCollection, page);
            TempData["SuccessMessage"] = "Page created successfully!";
            return RedirectToAction("Index");
        }

        [HttpGet("edit/{id}")]
        public async Task<IActionResult> Edit(string id)
        {
            var page = await _mongoService.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)}");

            // Debug: Check what's in the form
            foreach (var key in form.Keys)
            {
                if (key.StartsWith("ImageGallery") || key.StartsWith("TeamMembers"))
                {
                    Console.WriteLine($"[ADMIN-PAGES] {key} = {form[key]}");
                }
            }

            if (!ModelState.IsValid)
            {
                Console.WriteLine("[ADMIN-PAGES] ModelState is INVALID");
                foreach (var error in ModelState.Values.SelectMany(v => v.Errors))
                {
                    Console.WriteLine($"[ADMIN-PAGES] Error: {error.ErrorMessage}");
                }
                return View(page);
            }

            // Get existing page to preserve data
            var existingPage = await _mongoService.GetByIdAsync<Page>(_pagesCollection, id);
            if (existingPage == null)
            {
                Console.WriteLine($"[ADMIN-PAGES] Page not found: {id}");
                return NotFound();
            }

            // Update basic fields
            existingPage.PageName = page.PageName;
            existingPage.Title = page.Title;
            existingPage.Subtitle = page.Subtitle;
            existingPage.Content = page.Content;
            existingPage.IsActive = page.IsActive;
            existingPage.UpdatedAt = DateTime.UtcNow;
            existingPage.PageSlug = _slugService.GenerateSlug(page.PageName);

            // Manually parse ImageGallery from form
            existingPage.ImageGallery = new List<string>();
            foreach (var key in form.Keys.Where(k => k.StartsWith("ImageGallery[")))
            {
                var value = form[key].ToString();
                if (!string.IsNullOrEmpty(value))
                {
                    existingPage.ImageGallery.Add(value);
                }
            }

            // Manually parse TeamMembers from form
            existingPage.TeamMembers = new List<TeamMember>();
            var memberIndices = form.Keys
                .Where(k => k.StartsWith("TeamMembers[") && k.Contains("].Name"))
                .Select(k =>
                {
                    var match = System.Text.RegularExpressions.Regex.Match(k, @"TeamMembers\[(\d+)\]");
                    return match.Success ? int.Parse(match.Groups[1].Value) : -1;
                })
                .Where(i => i >= 0)
                .Distinct()
                .OrderBy(i => i)
                .ToList();

            foreach (var index in memberIndices)
            {
                var member = new TeamMember
                {
                    Name = form[$"TeamMembers[{index}].Name"].ToString(),
                    Role = form[$"TeamMembers[{index}].Role"].ToString(),
                    Bio = form[$"TeamMembers[{index}].Bio"].ToString(),
                    PhotoUrl = form[$"TeamMembers[{index}].PhotoUrl"].ToString()
                };
                existingPage.TeamMembers.Add(member);
            }

            Console.WriteLine($"[ADMIN-PAGES] Updating page: {existingPage.PageName} (Slug: {existingPage.PageSlug})");
            Console.WriteLine($"[ADMIN-PAGES] Title: {existingPage.Title}");
            Console.WriteLine($"[ADMIN-PAGES] Content length: {existingPage.Content?.Length ?? 0}");
            Console.WriteLine($"[ADMIN-PAGES] Image Gallery Count: {existingPage.ImageGallery.Count}");
            Console.WriteLine($"[ADMIN-PAGES] Team Members Count: {existingPage.TeamMembers.Count}");

            if (existingPage.ImageGallery.Any())
            {
                Console.WriteLine($"[ADMIN-PAGES] Gallery Images: {string.Join(", ", existingPage.ImageGallery)}");
            }

            if (existingPage.TeamMembers.Any())
            {
                foreach (var member in existingPage.TeamMembers)
                {
                    Console.WriteLine($"[ADMIN-PAGES] Team Member: {member.Name} - {member.Role} - Photo: {member.PhotoUrl}");
                }
            }

            await _mongoService.UpdateAsync(_pagesCollection, id, existingPage);
            TempData["SuccessMessage"] = "Page updated successfully!";
            return RedirectToAction("Index");
        }

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