using SharedKernel.Attributes;
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;

namespace Admin.Pages.Banner.List;

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

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

    public sealed class InputModel
    {
        [DisplayName("배너 위치 ID")]
        [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; } = null!;

        [DisplayName("첨부 이미지(Desktop)")]
        [AllowedExtensions("jpg,jpeg,png,gif,webp", ErrorMessage = "이미지 파일은 jpg, jpeg, png, gif, webp 형식이어야 합니다.")]
        public IFormFile? DesktopImageFile { get; set; }

        [DisplayName("첨부 이미지(Mobile)")]
        [AllowedExtensions("jpg,jpeg,png,gif,webp", ErrorMessage = "이미지 파일은 jpg, jpeg, png, gif, webp 형식이어야 합니다.")]
        public IFormFile? MobileImageFile { get; set; }

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

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

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

        [DisplayName("사용 기간 - 시작")]
        [DataType(DataType.DateTime)]
        public DateTime? StartAt { get; set; }

        [DisplayName("사용 기간 - 종료")]
        [DataType(DataType.DateTime)]
        public DateTime? EndAt { get; set; }
    }

    public async Task OnGetAsync(CancellationToken ct)
    {
        Positions = [.. (await mediator.Send(new GetBannerPositions.Query(), ct)).List.Select(p => new SelectListItem {
            Value = p.ID.ToString(),
            Text = $"[{p.Code}] {p.Subject}"
        })];

        QueryString = Request.QueryString.ToString();
    }

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

            await mediator.Send(new CreateBannerItem.Command(
                Input.PositionID,
                Input.Subject,
                Input.DesktopImageFile,
                Input.MobileImageFile,
                Input.Link,
                Input.Order,
                Input.IsActive,
                Input.StartAt,
                Input.EndAt
            ), ct);

            TempData["SuccessMessage"] = $"{Input.Subject} 배너가 등록되었습니다.";

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

            return Redirect($"/Banner/List/Write?{Request.QueryString}");
        }
    }
}