using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using bitforum.Models;
using bitforum.Models.Page;
using bitforum.Helpers;
using bitforum.Services;
using bitforum.Repository;
using bitforum.Constants;

namespace bitforum.Controllers.Page
{
    [Authorize]
    [Route("Page")]
    public class PopupController : Controller
    {
        private readonly ILogger<PopupController> _logger;
        private readonly IFileUploadService _fileUploadService;
        private readonly IRedisRepository _redisRepository;
        private readonly DefaultDbContext _db;
        private readonly string _IndexViewPath = "~/Views/Page/Popup/Index.cshtml";
        private readonly string _WriteViewPath = "~/Views/Page/Popup/Write.cshtml";
        private readonly string _EditViewPath = "~/Views/Page/Popup/Edit.cshtml";

        public PopupController(ILogger<PopupController> logger, IFileUploadService fileUploadService, IRedisRepository redisRepository, DefaultDbContext db)
        {
            _logger = logger;
            _fileUploadService = fileUploadService;
            _redisRepository = redisRepository;
            _db = db;
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpGet("Popup")]
        public IActionResult Index([FromQuery] int page = 1)
        {
            var popups = _db.Popup.OrderByDescending(c => c.ID).ToList();
            var data = new List<object>();

            if (popups.Count > 0)
            {
                foreach (var row in popups)
                {
                    string Expired = row switch
                    {
                        { StartAt: not null, EndAt: not null } => $"{row.StartAt.GetDateAt()} ~ {row.EndAt.GetDateAt()}",
                        { StartAt: not null, EndAt: null } => $"{row.StartAt.GetDateAt()}",
                        { StartAt: null, EndAt: not null } => $"~ {row.EndAt.GetDateAt()}",
                        _ => "[무기한]"
                    };

                    var entry = new
                    {
                        row.ID,
                        row.Subject,
                        row.Content,
                        row.Link,
                        Expired,
                        row.Order,
                        IsActive = (row.IsActive ? 'Y' : 'N'),
                        Views = row.Views.ToString("N0"),
                        UpdatedAt = row.UpdatedAt.GetDateAt(),
                        CreatedAt = row.CreatedAt.GetDateAt(),
                        EditURL = $"/Page/Popup/{row.ID}/Edit",
                        DeleteURL = $"/Page/Popup/{row.ID}/Delete"
                    };

                    data.Add(entry);
                }
            }

            ViewBag.Data = data;
            ViewBag.Total = (data?.Count ?? 0);
            ViewBag.Pagination = new Pagination(ViewBag.Total, page, 20, null);

            return View(_IndexViewPath);
        }

        [HttpGet("Popup/Write")]
        public IActionResult Write()
        {
            return View(_WriteViewPath);
        }

        [HttpPost("Popup/Create")]
        public async Task<IActionResult> Create(Popup request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("유효성 검사에 실패하였습니다.");
                }

                if (request.EndAt < request.StartAt)
                {
                    throw new Exception("사용 기간을 확인해주세요.");
                }

                request.Content = _fileUploadService.UploadEditorAsync(request.Content, null, UploadFolder.Popup).Result;
                request.UpdatedAt = null;
                request.CreatedAt = DateTime.UtcNow;

                _db.Popup.Add(request);

                int affectedRows = await _db.SaveChangesAsync();
                if (affectedRows <= 0)
                {
                    throw new Exception("팝업 등록 중 오류가 발생했습니다.");
                }

                await _redisRepository.DeleteAsync(RedisConst.PopupKey);

                string message = "팝업이 등록되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return Index();
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return View(_WriteViewPath, request);
            }
        }

        [HttpGet("Popup/{id}/Edit")]
        public async Task<IActionResult> Edit(int id)
        {
            try
            {
                if (id <= 0)
                {
                    throw new Exception("유효하지 않은 접근입니다.");
                }

                var popup = await _db.Popup.FirstAsync(c => c.ID == id);
                if (popup is null)
                {
                    throw new Exception("팝업 정보를 찾을 수 없습니다.");
                }

                return View(_EditViewPath, popup);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return Index();
            }
        }

        [HttpPost("Popup/Update")]
        public async Task<IActionResult> Update(Popup request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("유효성 검사에 실패하였습니다.");
                }

                if (request.EndAt < request.StartAt)
                {
                    throw new Exception("사용 기간을 확인해주세요.");
                }

                var popup = await _db.Popup.FirstAsync(c => c.ID == request.ID);
                if (popup is null)
                {
                    throw new Exception("팝업 정보를 찾을 수 없습니다.");
                }

                popup.Subject = request.Subject;
                popup.Content = _fileUploadService.UploadEditorAsync(request.Content, popup.Content, UploadFolder.Popup).Result;
                popup.IsActive = request.IsActive;
                popup.Link = request.Link;
                popup.Order = request.Order;
                popup.StartAt = request.StartAt;
                popup.EndAt = request.EndAt;
                popup.UpdatedAt = DateTime.UtcNow;

                int affectedRows = await _db.SaveChangesAsync();
                if (affectedRows <= 0)
                {
                    throw new Exception("팝업 수정 중 오류가 발생했습니다.");
                }

                await _redisRepository.DeleteAsync(RedisConst.PopupKey);

                string message = $"{popup.ID}번 팝업이 수정되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return await Edit(request.ID);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return View(_EditViewPath, request);
            }
        }

        [HttpGet("Popup/{id}/Delete")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                if (id <= 0)
                {
                    throw new Exception("유효하지 않은 문서 ID입니다.");
                }

                var popup = await _db.Popup.FindAsync(id);
                if (popup == null)
                {
                    throw new Exception("팝업 정보를 찾을 수 없습니다.");
                }

                _db.Popup.Remove(popup);

                int affectedRows = await _db.SaveChangesAsync();
                if (affectedRows <= 0)
                {
                    throw new Exception("팝업 삭제 중 오류가 발생했습니다.");
                }

                await _fileUploadService.CleanUpEditorImagesAsync(popup.Content);
                await _redisRepository.DeleteAsync(RedisConst.PopupKey);

                string message = "팝업이 삭제되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
            }

            return Index();
        }

        [HttpPost("Popup/Delete")]
        public async Task<IActionResult> Delete([FromForm] int[] ids)
        {
            try
            {
                if (ids == null || ids.Length <= 0)
                {
                    throw new Exception("유효하지 않은 접근입니다.");
                }

                foreach (var id in ids)
                {
                    var popup = await _db.Popup.FindAsync(id);
                    if (popup == null)
                    {
                        throw new Exception($"{id}번 팝업 정보를 찾을 수 없습니다.");
                    }

                    _db.Popup.Remove(popup);

                    int affectedRows = await _db.SaveChangesAsync();
                    if (affectedRows <= 0)
                    {
                        throw new Exception($"{id}번 팝업 삭제 중 오류가 발생했습니다.");
                    }

                    await _fileUploadService.CleanUpEditorImagesAsync(popup.Content);
                    await _redisRepository.DeleteAsync(RedisConst.PopupKey);
                }

                string message = $"{ids.Length}건의 팝업이 삭제되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
            }

            return Index();
        }
    }
}
