using SharedKernel.Helpers;
using SharedKernel.Extensions;
using Domain.Entities.Members.ValueObject;
using Application.Abstractions.Messaging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.Pages.Member.List;

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;

        [DisplayName("검색 조건")]
        [Range(1, 5, 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; }

        [DisplayName("성별")]
        public Gender? Gender { get; set; }

        [DisplayName("이메일 인증")]
        public int? IsEmailVerified { get; set; }

        [DisplayName("본인 인증")]
        public int? IsAuthCertified { get; set; }

        [DisplayName("탭")]
        public int Tab { get; set; } = 0;
    }

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

    public SearchMembers.Response.TabCounts Counts { get; set; } = new();

    public List<(
        int ID,
        string Email,
        string? Name,
        string? FullName,
        string? Icon,
        string? Phone,
        string? Birthday,
        string? Gender,
        string? GradeName,
        char IsEmailVerified,
        char IsAuthCertified,
        char IsDenied,
        char IsWithdraw,
        long Following,
        long Followed,
        string? LastLoginAt,
        string? LastLoginIp,
        string? UpdatedAt,
        string CreatedAt,
        string ViewURL,
        string ApproveURL,
        string EditURL
    )> List { get; set; } = [];

    public Pagination? Pagination { get; set; }

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

        var result = await mediator.Send(new SearchMembers.Query(
            Query.PageNum,
            Query.PerPage,
            Query.Search,
            Query.Keyword,
            Query.StartAt,
            Query.EndAt,
            Query.Gender,
            Query.IsEmailVerified,
            Query.IsAuthCertified,
            Query.Tab
        ), ct);

        Total = result.Total;
        Counts = result.Counts;

        var qs = Request.QueryString.ToString();

        List = [..result.List.Select(c => (
            c.ID,
            c.Email,
            Name: c.Name ?? "-",
            FullName: c.FullName ?? "-",
            c.Icon,
            c.Phone,
            Birthday: c.Birthday ?? "-",
            Gender: c.Gender ?? "-",
            GradeName: c.GradeName ?? "-",
            IsEmailVerified: c.IsEmailVerified ? 'Y' : 'N',
            IsAuthCertified: c.IsAuthCertified ? 'Y' : 'N',
            IsDenied: c.IsDenied ? 'Y' : 'N',
            IsWithdraw: c.IsWithdraw ? 'Y' : 'N',
            c.Following,
            c.Followed,
            LastLoginAt: c.LastLoginAt.GetDateAt() ?? "-",
            c.LastLoginIp,
            UpdatedAt: c.UpdatedAt.GetDateAt() ?? "-",
            CreatedAt: c.CreatedAt.GetDateAt(),
            ViewURL: $"/Member/List/View/{c.ID}{qs}",
            ApproveURL: $"/Member/List/Approve/{c.ID}{qs}",
            EditURL: $"/Member/List/Edit/{c.ID}{qs}"
        ))];

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

    public async Task<IActionResult> OnPostDeleteAsync(int[] ids, CancellationToken ct)
    {
        try
        {
            if (ids.Length == 0)
            {
                throw new Exception("삭제할 항목을 선택해주세요.");
            }

            await mediator.Send(new DeleteMember.Command(ids), ct);

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

        return RedirectToPage(Query);
    }
}