using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using bitforum.Helpers;
using bitforum.Models;
using bitforum.Models.Account;
using bitforum.Services;

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

        public GradeController(ILogger<GradeController> logger, IFileUploadService fileUploadService, DefaultDbContext db)
        {
            _logger = logger;
            _fileUploadService = fileUploadService;
            _db = db;
        }

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

        [HttpGet("Grade")]
        public IActionResult Index()
        {
            var memberGrades = _db.MemberGrade.OrderByDescending(c => c.Order).ToList();
            var data = new List<object>();

            if (memberGrades.Count > 0)
            {
                foreach (var row in memberGrades)
                {
                    data.Add(new
                    {
                        row.ID,
                        row.Image,
                        Name = $"{row.KorName}({row.EngName})",
                        row.Order,
                        RequiredExp = row.RequiredExp.ToString("N0"),
                        RequiredCoin = row.RequiredCoin.ToString("N0"),
                        IsActive = (row.IsActive ? 'Y' : 'N'),
                        UpdatedAt = row.UpdatedAt.GetDateAt(),
                        CreatedAt = row.CreatedAt.GetDateAt(),
                        MemberRows = _db.Member.Count(c => c.GradeID == row.ID),
                        EditURL = $"/Member/Grade/{row.ID}/Edit",
                        DeleteURL = $"/Member/Grade/{row.ID}/Delte"
                    });
                }
            }

            ViewBag.Data = data;
            ViewBag.Total = (data?.Count ?? 0);

            return View(_IndexViewPath);
        }

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

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

                request.Image = await _fileUploadService.UploadImageAsync(Image, UploadFolder.Grade);
                request.UpdatedAt = null;
                request.CreatedAt = DateTime.UtcNow;

                _db.MemberGrade.Add(request);

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

                string message = "회원등급이 등록되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return Redirect("/Member/Grade");
            }
            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("Grade/{id}/Edit")]
        public async Task<IActionResult> Edit(int id)
        {
            try
            {
                if (id <= 0)
                {
                    throw new Exception("유효하지 않은 접근입니다.");
                }

                var memberGrade = await _db.MemberGrade.FirstAsync(c => c.ID == id);
                if (memberGrade is null)
                {
                    throw new Exception("회원등급 정보를 찾을 수 없습니다.");
                }

                return View(_EditViewPath, memberGrade);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return Redirect("/Member/Grade");
            }
        }

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

                var memberGrade = await _db.MemberGrade.FirstAsync(c => c.ID == request.ID);
                if (memberGrade is null)
                {
                    throw new Exception("회원등급 정보를 찾을 수 없습니다.");
                }

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

                memberGrade.KorName = request.KorName;
                memberGrade.EngName = request.EngName;
                memberGrade.Description = request.Description;
                memberGrade.Order = request.Order;
                memberGrade.RequiredExp = request.RequiredExp;
                memberGrade.RequiredCoin = request.RequiredCoin;
                memberGrade.IsActive = request.IsActive;
                memberGrade.UpdatedAt = DateTime.UtcNow;

                _db.MemberGrade.Update(memberGrade);

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

                string message = "회원등급이 수정되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return Redirect($"/Member/Grade/{request.ID}/Edit");
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
                return await Edit(request.ID);
            }
        }

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

                var memberGrade = await _db.MemberGrade.FindAsync(id);
                if (memberGrade == null)
                {
                    throw new Exception("회원등급 정보를 찾을 수 없습니다.");
                }

                _fileUploadService.RemoveFile(memberGrade.Image);
                _db.MemberGrade.Remove(memberGrade);

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

                _fileUploadService.RemoveFile(memberGrade.Image);

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

            return Redirect("/Member/Grade");
        }
    }
}
