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

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

        public ItemController(ILogger<ItemController> 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 });
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            ViewBag.QueryString = _queryString = string.Join("&", QueryHelpers.ParseQuery(HttpContext.Request.QueryString.Value).Select(r => $"{r.Key}={string.Join(",", r.Value)}"));

            base.OnActionExecuting(context);
        }

        [HttpGet("Item/{positionID?}")]
        public IActionResult Index(int? positionID, [FromQuery] int page = 1)
        {
            ViewBag.positionID = positionID;

            // 위치 목록
            ViewBag.BannerPositions = _db.BannerPosition.Include(c => c.BannerItem).Where(c => c.IsActive).ToList();

            // 배너 목록
            var bannerItemQuery = _db.BannerItem.Include(c => c.BannerPosition).OrderBy(c => c.Order).AsQueryable();
            if (positionID.HasValue)
            {
                bannerItemQuery = bannerItemQuery.Where(c => c.PositionID == positionID);
            }

            var bannerItems = bannerItemQuery.ToList();
            var data = new List<object>();

            if (bannerItems.Count > 0)
            {
                foreach (var row in bannerItems)
                {
                    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,
                        BannerPositionName = row.BannerPosition?.Subject,
                        Expired,
                        row.Subject,
                        row.Image,
                        row.Width,
                        row.Height,
                        row.Link,
                        row.Order,
                        IsActive = (row.IsActive ? 'Y' : 'N'),
                        Views = row.Views.ToString("N0"),
                        UpdatedAt = row.UpdatedAt.GetDateAt(),
                        CreatedAt = row.CreatedAt.GetDateAt(),
                        EditURL = $"/Page/Banner/Item/{row.ID}/Edit?{_queryString}",
                        DeleteURL = $"/Page/Banner/Item/{row.ID}/Delete?{_queryString}"
                    };

                    data.Add(entry);
                }
            }

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

            return View(_IndexViewPath);
        }

        [HttpGet("Item/Write")]
        public IActionResult Write()
        {
            ViewBag.BannerPositions = _db.BannerPosition.Where(c => c.IsActive).ToList();

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

                if (request.PositionID <= 0 || !_db.BannerPosition.Any(c => c.ID == request.PositionID))
                {
                    throw new Exception("유효한 위치를 선택하세요.");
                }

                // 이미지 저장
                request.Image = await _fileUploadService.UploadImageAsync(Image, UploadFolder.Banner);
                request.UpdatedAt = null;
                request.CreatedAt = DateTime.UtcNow;

                _db.BannerItem.Add(request);

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

                await _redisRepository.DeleteAsync(RedisConst.BannerKey);

                string message = "배너가 등록되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return Redirect($"/Page/Banner/Item?{_queryString}");
            }
            catch (ArgumentException e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return Write();
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return Write();
            }
        }

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

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

                // 위치 목록
                ViewBag.BannerPositions = new SelectList(_db.BannerPosition.Where(c => c.IsActive).ToList(), "ID", "Subject", bannerItem.PositionID);

                return View(_EditViewPath, bannerItem);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return Redirect($"/Page/Banner/Item?{_queryString}");
            }
        }

        [HttpPost("Item/Update")]
        public async Task<IActionResult> Update(BannerItem request, IFormFile? Image, [FromForm] bool IsImageRemove = false)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("유효성 검사에 실패하였습니다.");
                }

                if (request.PositionID <= 0 || !_db.BannerPosition.Any(c => c.ID == request.PositionID))
                {
                    throw new Exception("유효한 분류를 선택하세요.");
                }

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

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

                // 이미지 저장
                if (IsImageRemove)
                {
                    // 실제 파일 삭제
                    _fileUploadService.RemoveFile(bannerItem.Image);
                    bannerItem.Image = null;
                }
                else if (Image is not null)
                {
                    bannerItem.Image = await _fileUploadService.UploadImageAsync(Image, UploadFolder.Banner);
                }

                bannerItem.PositionID = request.PositionID;
                bannerItem.Subject = request.Subject;
                bannerItem.Width = request.Width;
                bannerItem.Height = request.Height;
                bannerItem.Link = request.Link;
                bannerItem.Order = request.Order;
                bannerItem.IsActive = request.IsActive;
                bannerItem.StartAt = request.StartAt;
                bannerItem.EndAt = request.EndAt;
                bannerItem.UpdatedAt = DateTime.UtcNow;

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

                await _redisRepository.DeleteAsync(RedisConst.BannerKey);

                string message = "배너가 수정되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return Redirect($"/Page/Banner/Item/{request.ID}/Edit?{_queryString}");
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return await Edit(request.ID);
            }
        }

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

                var bannerItem = await _db.BannerItem.FindAsync(id);
                if (bannerItem == null)
                {
                    throw new Exception("배너 정보를 찾을 수 없습니다.");
                }

                _db.BannerItem.Remove(bannerItem);

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

                _fileUploadService.RemoveFile(bannerItem.Image);
                await _redisRepository.DeleteAsync(RedisConst.BannerKey);

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

            return Redirect($"/Page/Banner/Item?{_queryString}");
        }

        [HttpPost("Item/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 bannerItem = await _db.BannerItem.FindAsync(id);
                    if (bannerItem == null)
                    {
                        throw new Exception($"{id}번 배너 정보를 찾을 수 없습니다.");
                    }

                    _db.BannerItem.Remove(bannerItem);

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

                    _fileUploadService.RemoveFile(bannerItem.Image);
                    await _redisRepository.DeleteAsync(RedisConst.BannerKey);
                }

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

            return Redirect($"/Page/Banner/Item?{_queryString}");
        }
    }
}
