using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using bitforum.Models;
using bitforum.Models.Page;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace bitforum.Controllers.Page
{
    [Authorize]
    [Route("Page")]
    public class PopupController : Controller
    {
        private readonly ILogger<PopupController> _logger;
        private readonly DefaultDbContext _db;
        private readonly IConfiguration _config;
        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, DefaultDbContext db, IConfiguration config)
        {
            _logger = logger;
            _db = db;
            _config = config;
        }

        [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)
        {
            ViewBag.Popups = _db.Popup.OrderByDescending(c => c.ID).ToList();
            ViewBag.Total = ViewBag.Popups.Count;
            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.UpdatedAt = null;
                request.CreatedAt = DateTime.Now;

                _db.Popup.Add(request);

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

                string message = "팝업이 정상적으로 등록되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                TempData["ErrorMessages"] = 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)
            {
                _logger.LogError(e, e.Message);
                TempData["ErrorMessages"] = e.Message;
                return RedirectToAction("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 = request.Content;
                popup.IsActive = request.IsActive;
                popup.Link = request.Link;
                popup.Order = request.Order;
                popup.StartAt = request.StartAt;
                popup.EndAt = request.EndAt;
                popup.UpdatedAt = DateTime.Now;

                _db.Popup.Update(popup);

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

                string message = "팝업이 정상적으로 수정되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return RedirectToAction("Edit", new { request.ID });
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                TempData["ErrorMessages"] = e.Message;
                return View(_EditViewPath, request);
            }
        }

        [HttpGet("Popup/Delete/{id}")]
        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("팝업 삭제 중 오류가 발생했습니다.");
                }

                string message = "팝업이 정상적으로 삭제되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                TempData["ErrorMessages"] = 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("팝업 정보를 찾을 수 없습니다.");
                    }

                    _db.Popup.Remove(popup);

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

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