using SharedKernel.Extensions;
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.Board.List;

public class EditModel(IMediator mediator) : PageModel
{
    [BindProperty]
    public string? QueryString { get; set; }
    public List<SelectListItem> BoardGroupList { get; set; } = [];

    public int BoardID { get; set; }
    public List<(int ID, string Name)> BoardList { get; set; } = [];

    [BindProperty]
    public InputModel Input { get; set; } = new();

    public sealed class InputModel
    {
        [DisplayName("ID")]
        [Required(ErrorMessage = "{0}은 필수입니다.")]
        public int ID { get; set; }

        [DisplayName("게시판 분류")]
        [Required(ErrorMessage = "{0}은 필수입니다.")]
        public int BoardGroupID { get; set; }

        [DisplayName("주소(Code)")]
        [Required(ErrorMessage = "{0}은 필수입니다.")]
        [StringLength(70, ErrorMessage = "{0}은 {1}자 이내로 입력하세요.")]
        public string Code { get; set; } = null!;

        [DisplayName("게시판 명")]
        [Required(ErrorMessage = "{0}은 필수입니다.")]
        [StringLength(70, ErrorMessage = "{0}은 {1}자 이내로 입력하세요.")]
        public string Name { get; set; } = null!;

        [DisplayName("순서")]
        [Required(ErrorMessage = "{0}은 필수입니다.")]
        [Range(-999, 999, ErrorMessage = "{0} 범위는 {2} ~ {1} 입니다.")]
        public short Order { get; set; } = 0;

        [DisplayName("검색 여부")]
        public bool IsSearch { get; set; } = false;

        [DisplayName("사용 여부")]
        public bool IsActive { get; set; } = false;
    }

    public async Task OnGetAsync(int id, CancellationToken ct)
    {
        BoardGroupList = [..(await mediator.Send(new GetBoardGroups.Query(), ct)).List.Select(c => new SelectListItem
        {
            Value = c.ID.ToString(),
            Text = c.Name
        })];

        var result = await mediator.Send(new GetBoard.Query(id), ct);

        BoardID = result.ID;

        // 같은 분류의 게시판 목록 조회
        var boards = await mediator.Send(new SearchBoards.Query(null, null, 1, 100), ct);
        BoardList = [..boards.List.Select(c => (c.ID, c.Name))];

        Input = new InputModel
        {
            ID = result.ID,
            BoardGroupID = result.BoardGroupID,
            Code = result.Code,
            Name = result.Name,
            Order = result.Order,
            IsSearch = result.IsSearch,
            IsActive = result.IsActive
        };

        QueryString = Request.QueryString.ToString();
    }

    public async Task<IActionResult> OnPostAsync(CancellationToken ct)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                throw new Exception(ModelState.GetErrorMessages());
            }

            await mediator.Send(new UpdateBoard.Command(
                Input.ID,
                Input.BoardGroupID,
                Input.Code,
                Input.Name,
                Input.Order,
                Input.IsSearch,
                Input.IsActive
            ), ct);

            TempData["SuccessMessage"] = $"{Input.Name} 게시판이 수정되었습니다.";
        }
        catch (Exception e)
        {
            TempData["ErrorMessages"] = e.Message;
        }

        return Redirect($"/Forum/Board/List/Edit/{Input.ID}{Request.QueryString}");
    }
}