using SharedKernel.Extensions;
using SharedKernel.Helpers;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.Pages.Forum.Posts.List
{
    public class IndexModel(IMediator mediator) : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public QueryParams Query { get; set; } = new();

        public sealed class QueryParams
        {
            public int? BoardID { get; set; }
            public int? BoardPrefixID { get; set; }
            public int? Search { get; set; }
            public string? Keyword { get; set; }
            public string? StartAt { get; set; }
            public string? EndAt { get; set; }
            public int? Sort { get; set; }
            public bool? IsNotice { get; set; }
            public bool? IsSecret { get; set; }
            public bool? IsReply { get; set; }
            public bool? IsDeleted { get; set; }
            public bool? IsQnA { get; set; }

            [Range(1, int.MaxValue)]
            [DisplayName("페이지 번호")]
            public int PageNum { get; set; } = 1;

            [Range(1, 100)]
            [DisplayName("페이지 목록 수")]
            public ushort PerPage { get; set; } = 20;
        }

        public int Total { get; set; }

        public List<SelectListItem> BoardList { get; set; } = [];

        public List<(
            int No,
            int ID,
            int BoardID,
            string BoardName,
            string? BoardPrefixName,
            int? BoardPrefixID,
            string Subject,
            string? Thumbnail,
            string? Name,
            string? SID,
            bool IsNotice,
            bool IsSecret,
            bool IsQnA,
            bool IsReply,
            bool IsSpeaker,
            bool IsAnonymous,
            bool IsActive,
            bool IsDeleted,
            int Views,
            int Likes,
            int Dislikes,
            int Comments,
            byte Images,
            byte Medias,
            byte Files,
            byte Tags,
            string? UpdatedAt,
            string CreatedAt,
            string ViewURL
        )> Data { get; set; } = [];

        public Pagination? Pagination { get; set; }

        public async Task OnGetAsync(CancellationToken ct)
        {
            if (!ModelState.IsValid)
            {
                return;
            }

            // 게시판 목록 조회
            var boards = await mediator.Send(new SearchBoards.Query(null, null, 1, 500), ct);

            BoardList = [..boards.List.Select(c => new SelectListItem
            {
                Value = c.ID.ToString(),
                Text = $"[{c.BoardGroupName}] {c.Name}"
            })];

            var result = await mediator.Send(new SearchPosts.Query(
                Query.BoardID,
                Query.BoardPrefixID,
                Query.Search,
                Query.Keyword,
                Query.StartAt,
                Query.EndAt,
                Query.Sort,
                Query.IsNotice,
                Query.IsSecret,
                Query.IsReply,
                Query.IsDeleted,
                Query.IsQnA,
                Query.PageNum,
                Query.PerPage
            ), ct);

            Total = result.Total;
            Data = [..result.List.Select(c => (
                c.Num,
                c.ID,
                c.BoardID,
                c.BoardName,
                c.BoardPrefixName,
                c.BoardPrefixID,
                c.Subject,
                c.Thumbnail,
                c.Name,
                c.SID,
                c.IsNotice,
                c.IsSecret,
                c.IsQnA,
                c.IsReply,
                c.IsSpeaker,
                c.IsAnonymous,
                IsActive: !c.IsDeleted,
                c.IsDeleted,
                c.Views,
                c.Likes,
                c.Dislikes,
                c.Comments,
                c.Images,
                c.Medias,
                c.Files,
                c.Tags,
                c.UpdatedAt.GetDateAt() ?? "-",
                c.CreatedAt.GetDateAt(),
                ViewURL: $"/Forum/Posts/List/View/{c.ID}{Request.QueryString}"
            ))];

            Pagination = new Pagination(result.Total, Query.PageNum, Query.PerPage);
        }

        public async Task<IActionResult> OnPostDeleteAsync(int[] ids, CancellationToken ct)
        {
            try
            {
                await mediator.Send(new DeletePost.Command(ids), ct);

                TempData["SuccessMessage"] = $"{ids.Length}건이 삭제되었습니다.";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return RedirectToPage("/Forum/Posts/List/Index", Query);
        }
    }
}