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

namespace Admin.Pages.Member.Grade
{
    public class EditModel(IMediator mediator) : PageModel
    {
        [BindProperty]
        public InputModel Input { get; set; } = new();

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

            public string? Image { get; set; }

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

            [DisplayName("한글 명")]
            [DataType(DataType.Text)]
            [Required(ErrorMessage = "{0}은(는) 필수입니다.")]
            [StringLength(240, ErrorMessage = "{0}은(는) {1}자 이하로 입력하세요.")]
            public string KorName { get; set; } = default!;

            [DisplayName("영문 명")]
            [DataType(DataType.Text)]
            [Required(ErrorMessage = "{0}은(는) 필수입니다.")]
            [StringLength(120, ErrorMessage = "{0}은(는) {1}자 이하로 입력하세요.")]
            public string EngName { get; set; } = default!;

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

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

            [DisplayName("누적 후원 횟수")]
            [Required(ErrorMessage = "{0}은(는) 필수입니다.")]
            [Range(0, 1000000000, ErrorMessage = "{0} 입력 범위는 {1} ~ {2} 입니다.")]
            public long TotalDonationCount { get; set; } = 0;

            [DisplayName("누적 후원 금액")]
            [Required(ErrorMessage = "{0}은(는) 필수입니다.")]
            [Range(0, 1000000000, ErrorMessage = "{0} 입력 범위는 {1} ~ {2} 입니다.")]
            public int TotalDonationAmount { get; set; } = 0;

            [DisplayName("표시 색상")]
            [Required(ErrorMessage = "{0}은(는) 필수입니다.")]
            [StringLength(7, MinimumLength = 4, ErrorMessage = "{0}은(는) {2}자 이상 {1}자 이하로 입력하세요.")]
            public string TextColor { get; set; } = "#000000";

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

            public string? UpdatedAt { get; set; }
            public string CreatedAt { get; set; } = default!;
        }

        public async Task OnGetAsync(int id, CancellationToken ct)
        {
            var result = await mediator.Send(new GetMemberGrade.Query(id), ct);

            Input = new InputModel
            {
                ID = result.ID,
                Image = result.Image,
                KorName = result.KorName,
                EngName = result.EngName,
                Description = result.Description,
                Order = result.Order,
                TotalDonationCount = result.RequiredAttendance,
                TotalDonationAmount = result.RequiredExp,
                TextColor = result.TextColor ?? "#000000",
                IsActive = result.IsActive,
                UpdatedAt = result.UpdatedAt.GetDateAt() ?? "-",
                CreatedAt = result.CreatedAt.GetDateAt()
            };
        }

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

                await mediator.Send(new UpdateMemberGrade.Command(
                    Input.ID,
                    Input.KorName,
                    Input.EngName,
                    Input.Description,
                    Input.Order,
                    Input.ImageFile,
                    isImageRemove,
                    Input.TextColor,
                    Input.TotalDonationAmount,
                    Input.TotalDonationCount,
                    Input.IsActive
                ), ct);

                TempData["SuccessMessage"] = $"{Input.KorName} 회원등급이 수정되었습니다.";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return Redirect($"/Member/Grade/Edit/{Input.ID}");
        }
    }
}
