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

namespace Admin.Pages.Banner.List;

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

    public List<(int ID, string Subject, int BannerItemRows)> Positions { get; set; } = [];

    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;

        [DisplayName("배너 위치")]
        public int? PositionID { get; set; }

        [DisplayName("검색어")]
        public string? Keyword { get; set; }
    }

    public int Total { get; set; }

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

    public Pagination? Pagination { get; set; }

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

        Positions = [.. (await mediator.Send(new GetBannerPositions.Query(), ct)).List.Select(c => (c.ID, c.Subject, c.BannerItemRows))];

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

        Total = result.Total;
        List = [..result.List.Select(c => (
            c.Num,
            c.ID,
            c.PositionCode,
            c.PositionSubject,
            c.Subject,
            c.Order,
            c.IsActive ? 'Y' : 'N',
            c.UpdatedAt.GetDateAt() ?? "-",
            c.CreatedAt.GetDateAt(),
            EditURL: $"/Banner/List/Edit/{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 DeleteBannerItem.Command(ids), ct);

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

        return RedirectToPage("/Banner/List/Index", Query);
    }
}