using SharedKernel;
using SharedKernel.Helpers;
using SharedKernel.Extensions;
using Application.Abstractions.Messaging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;

namespace Admin.Pages.Forum.Attachments.PostImage
{
    public class IndexModel(IMediator mediator, IOptions<AppSettings> options) : PageModel
    {
        public readonly string ApiURL = options.Value.App.ApiURL;

        [BindProperty(SupportsGet = true)]
        public QueryParams Query { get; set; } = new();

        public sealed class QueryParams
        {
            public int? BoardID { get; set; }
            public int? PostID { get; set; }
            public int? Search { get; set; }
            public string? Keyword { get; set; }
            public string? StartAt { get; set; }
            public string? EndAt { get; set; }
            public bool? IsDisabled { 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; } = 0;
        public List<SelectListItem> BoardList { get; set; } = [];

        public List<(
            int Num,
            int ID,
            int BoardID,
            string BoardName,
            int PostID,
            string PostSubject,
            string FileName,
            string Url,
            string? Extension,
            long? Size,
            short? Width,
            short? Height,
            bool IsDisabled,
            string CreatedAt
        )> List { 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 SearchPostImages.Query(
                Query.BoardID, Query.PostID, Query.Search, Query.Keyword,
                Query.IsDisabled, Query.StartAt, Query.EndAt,
                Query.PageNum, Query.PerPage
            ), ct);

            Total = result.Total;
            List = [..result.List.Select(c => (
                c.Num,
                c.ID,
                c.BoardID,
                c.BoardName,
                c.PostID,
                c.PostSubject,
                c.FileName,
                c.Url,
                c.Extension,
                c.Size,
                c.Width,
                c.Height,
                c.IsDisabled,
                c.CreatedAt.GetDateAt()
            ))];

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

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

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

            return RedirectToPage("/Forum/Attachments/PostImage/Index", Query);
        }

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

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

            return RedirectToPage("/Forum/Attachments/PostImage/Index", Query);
        }

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

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

            return RedirectToPage("/Forum/Attachments/PostImage/Index", Query);
        }
    }
}