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

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

        public sealed class InputModel
        {
            [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("순서")]
            [Range(-9999, 9999, ErrorMessage = "{0}은 {1}에서 {2} 사이의 값이어야 합니다.")]
            public short Order { get; set; } = 0;

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

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

            Categories = (await mediator.Send(new GetFaqCategories.Query(), ct)).List
                        .Select(c => new SelectListItem
                        {
                            Value = c.ID.ToString(),
                            Text = $"[{c.Code}] {c.Subject}",
                            Selected = categoryID.HasValue && c.ID == categoryID.Value
                        })
                        .ToList();

            if (categoryID.HasValue)
            {
                Input.CategoryID = categoryID.Value;
            }
        }

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

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

                await mediator.Send(command, ct);

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

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

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