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.Faq.List
{
    public class EditModel(IMediator mediator) : PageModel
    {
        [BindProperty]
        public string? QueryString { get; set; }
        public List<SelectListItem> Categories { get; private set; } = [];

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

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

            [DisplayName("FAQ 분류")]
            [Required(ErrorMessage = "{0}는 필수입니다.")]
            public int CategoryID { get; set; }

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

            [DisplayName("답변")]
            [DataType(DataType.Html)]
            public string? Answer { get; set; }

            [DisplayName("순서")]
            [Required(ErrorMessage = "{0}는 필수입니다.")]
            [Range(-9999, 9999, ErrorMessage = "{0}은 {1}에서 {2} 사이의 값이어야 합니다.")]
            public short Order { get; set; } = 0;

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

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

        private async Task<List<SelectListItem>> GetCategories(CancellationToken ct)
        {
            return [..(await mediator.Send(new GetFaqCategories.Query(), ct)).List
                   .Select(c => new SelectListItem
                   {
                       Value = c.ID.ToString(),
                       Text = $"[{c.Code}] {c.Subject}"
                   })];
        }

        public async Task<IActionResult> OnGetAsync(int id, CancellationToken ct)
        {
            QueryString = HttpContext.Request.QueryString.HasValue ? HttpContext.Request.QueryString.Value!.TrimStart('?') : "";

            Categories = await GetCategories(ct);

            var item = await mediator.Send(new GetFaqItem.Query(id), ct);
            if (item is null)
            {
                TempData["ErrorMessages"] = "해당 FAQ를 찾을 수 없습니다.";
                return RedirectToPage("/Faq/List/Index");
            }

            Input.ID = item.ID;
            Input.CategoryID = item.CategoryID;
            Input.Question = item.Question;
            Input.Answer = item.Answer;
            Input.Order = item.Order;
            Input.IsActive = item.IsActive;
            Input.UpdatedAt = item.UpdatedAt.GetDateAt();
            Input.CreatedAt = item.CreatedAt.GetDateAt();

            return Page();
        }

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

                var command = new UpdateFaqItem.Command(
                    Input.CategoryID,
                    Input.ID,
                    Input.Question,
                    Input.Answer,
                    Input.Order,
                    Input.IsActive
                );

                await mediator.Send(command, ct);

                TempData["SuccessMessage"] = $"{Input.Question} FAQ가 수정되었습니다.";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return Redirect($"/Faq/List/Edit/{Input.ID}?{QueryString}");
        }
    }
}