using SharedKernel.Helpers;
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.Wallet.List;

public class IndexModel(IMediator mediator) : PageModel
{
    [BindProperty(SupportsGet = true)]
    public QueryParams Parameter { 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;

        [DisplayName("검색 조건")]
        [Range(1, 4, ErrorMessage = "{0}이(가) 올바르지 않습니다.")]
        public int? Search { get; set; }

        [DisplayName("검색어")]
        [MaxLength(255, ErrorMessage = "{0}은(는) {1}자 이하로 입력하세요.")]
        public string? Keyword { get; set; }

        [DisplayName("시작일")]
        public string? StartAt { get; set; }

        [DisplayName("종료일")]
        public string? EndAt { get; set; }
    }

    public int Total { get; set; }

    public List<(
        int Num,
        int ID,
        int MemberID,
        string MemberEmail,
        string MemberName,
        string Balance,
        string DonationBalance,
        string UpdatedAt,
        string CreatedAt,
        string ChargeURL
    )> List { get; set; } = [];

    public Pagination? Pagination { get; set; }

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

        var result = await mediator.Send(new SearchWallets.Query(
            Parameter.PageNum,
            Parameter.PerPage,
            Parameter.Search,
            Parameter.Keyword,
            Parameter.StartAt,
            Parameter.EndAt
        ), ct);

        Total = result.Total;

        var qs = Request.QueryString.ToString();

        List = [..result.List.Select(c => (
            c.Num,
            c.ID,
            c.MemberID,
            c.MemberEmail,
            MemberName: c.MemberName ?? "-",
            Balance: c.Balance.ToString("N0"),
            DonationBalance: c.DonationBalance.ToString("N0"),
            UpdatedAt: c.UpdatedAt.GetDateAt() ?? "-",
            CreatedAt: c.CreatedAt.GetDateAt(),
            ChargeURL: $"/Member/Wallet/List/View/{c.ID}{qs}"
        ))];

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