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

namespace Admin.Pages.Popup;

public class IndexModel(IMediator mediator) : PageModel
{
    [BindProperty(SupportsGet = true)]
    public QueryParams Query { get; set; } = new();

    public sealed class QueryParams
    {
        [Range(1, int.MaxValue)]
        [DisplayName("페이지 번호")]
        public int PageNum { get; set; } = 1;

        [Range(1, 100)]
        [DisplayName("페이지 당 수")]
        public ushort PerPage { get; set; } = 10;
    }

    public int Total { get; set; } = 0;

    public List<(
        int Num,
        int ID,
        string PositionCode,
        string PositionSubject,
        string Subject,
        string? Link,
        string? StartAt,
        string? EndAt,
        short Order,
        bool IsActive,
        string? UpdatedAt,
        string CreatedAt,
        string EditURL,
        string DeleteURL
    )> List { get; set; } = [];

    public Pagination? Pagination { get; set; }

    public async Task OnGetAsync(CancellationToken ct)
    {
        if (!ModelState.IsValid)
        {
            return;
        }

        var result = await mediator.Send(new SearchPopups.Query(Query.PageNum, Query.PerPage), ct);

        Total = result.Total;
        List = [.. result.List.Select(c => (
            c.Num,
            c.ID,
            c.PositionCode,
            c.PositionSubject,
            c.Subject,
            c.Link ?? "-",
            c.StartAt ?? "-",
            c.EndAt ?? "-",
            c.Order,
            c.IsActive,
            c.UpdatedAt,
            c.CreatedAt,
            EditURL: $"/Popup/Edit/{c.ID}{Request.QueryString}",
            DeleteURL: $"/Popup/Delete/{c.ID}{Request.QueryString}"
        ))];

        Pagination = new Pagination(result.Total, Query.PageNum, Query.PerPage);
    }

    public async Task<IActionResult> OnPostDeleteAsync(int[] ids, CancellationToken ct)
    {
        try
        {
            await mediator.Send(new DeletePopup.Command(ids), ct);

            TempData["SuccessMessage"] = $"{ids.Length}개 팝업이 삭제되었습니다.";
        }
        catch (Exception e)
        {
            TempData["ErrorMessages"] = e.Message;
        }

        return RedirectToPage("/Popup/Index", Query);
    }
}