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.Popup;

public class WriteModel(IMediator mediator) : PageModel
{
    public string QueryString { get; private set; } = "";

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

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

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

        [DisplayName("제목")]
        [DataType(DataType.Text)]
        [Required(ErrorMessage = "{0}은 필수입니다.")]
        [StringLength(255, ErrorMessage = "{0}은 {1}자 이하로 입력하세요.")]
        public string Subject { get; set; } = default!;

        [DisplayName("내용")]
        [DataType(DataType.Html)]
        [StringLength(4000, ErrorMessage = "{0}은 {1}자 이하로 입력하세요.")]
        public string? Content { get; set; }

        [DisplayName("주소")]
        [DataType(DataType.Url)]
        [StringLength(255, ErrorMessage = "{0}은 {1}자 이하로 입력하세요.")]
        public string? Link { get; set; }

        [DisplayName("시작 일시")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-ddTHH:mm}", ApplyFormatInEditMode = true)]
        public DateTime? StartAt { get; set; }

        [DisplayName("종료 일시")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-ddTHH:mm}", ApplyFormatInEditMode = true)]
        public DateTime? EndAt { get; set; }

        [DisplayName("순서")]
        [Range(-9999, 9999)]
        public short Order { get; set; }

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

    public async Task OnGetAsync(CancellationToken ct)
    {
        QueryString = HttpContext.Request.QueryString.HasValue ? HttpContext.Request.QueryString.Value!.TrimStart('?') : "";

        await LoadPositionsAsync(ct);
    }

    public async Task<IActionResult> OnPostAsync(CancellationToken ct)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                throw new Exception("유효성 검사에 실패했습니다.");
            }

            var command = new CreatePopup.Command(
                Input.PositionID,
                Input.Subject,
                Input.Content,
                Input.Link,
                Input.StartAt,
                Input.EndAt,
                Input.Order,
                Input.IsActive
            );

            await mediator.Send(command, ct);

            TempData["SuccessMessage"] = $"{Input.Subject} 팝업이 등록되었습니다.";

            return RedirectToPage("/Popup/Index");
        }
        catch (Exception e)
        {
            TempData["ErrorMessages"] = e.Message;

            await LoadPositionsAsync(ct);

            return Redirect($"/Popup/Write?{QueryString}");
        }
    }

    private async Task LoadPositionsAsync(CancellationToken ct)
    {
        var result = await mediator.Send(new GetPopupPositions.Query(), ct);

        Positions = [..result.List.Select(x => new SelectListItem(
            x.Subject,
            x.ID.ToString())
        )];
    }
}