using Microsoft.AspNetCore.Components;
using MudBlazor;
using Google.Protobuf.WellKnownTypes;
using BackOffice.Pages.Club.Components;
using CMSMicroservice.Protobuf.Protos.ClubMembership;
using Microsoft.JSInterop;
using System.Text;
using DateTimeConverterCL;

namespace BackOffice.Pages.Club;

public partial class ClubMembers
{
    [Inject] public ClubMembershipContract.ClubMembershipContractClient ClubContract { get; set; }
    [Inject] public IJSRuntime JsRuntime { get; set; }

    private MudDataGrid<ClubMembershipModel> _gridData;
    private bool _filterIsActive = true;
    private long? _filterUserId;

    private async Task<GridData<ClubMembershipModel>> ServerReload(GridState<ClubMembershipModel> state)
    {
        try
        {
            var request = new GetAllClubMembershipsRequest
            {
                PageIndex = state.Page + 1,
                PageSize = state.PageSize
            };

            // Always use the filter value since it's now a bool (not nullable)
            request.IsActive = _filterIsActive;

            if (_filterUserId.HasValue && _filterUserId.Value > 0)
                request.UserId = _filterUserId.Value;

            var result = await ClubContract.GetAllClubMembershipsAsync(request);

            if (result?.Models != null && result.Models.Any())
            {
                return new GridData<ClubMembershipModel>
                {
                    Items = result.Models.ToList(),
                    TotalItems = (int)result.MetaData.TotalCount
                };
            }

            return new GridData<ClubMembershipModel>();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری داده‌ها: {ex.Message}", Severity.Error);
            return new GridData<ClubMembershipModel>();
        }
    }

    private async Task ApplyFilter()
    {
        if (_gridData != null)
        {
            await _gridData.ReloadServerData();
        }
    }

    private async Task ViewDetails(ClubMembershipModel member)
    {
        var parameters = new DialogParameters
        {
            ["Member"] = member
        };

        await DialogService.ShowAsync<MemberDetailsDialog>("جزئیات عضویت", parameters, new DialogOptions
        {
            CloseButton = true,
            MaxWidth = MaxWidth.Medium,
            FullWidth = true
        });
    }

    private async Task DeactivateMembership(ClubMembershipModel member)
    {
        var parameters = new DialogParameters
        {
            ["UserId"] = member.UserId,
            ["UserName"] = member.UserName
        };

        var dialog = await DialogService.ShowAsync<DeactivateClubDialog>("غیرفعال‌سازی عضویت", parameters, new DialogOptions
        {
            CloseButton = true,
            MaxWidth = MaxWidth.Small,
            FullWidth = true
        });

        var result = await dialog.Result;
        if (!result.Canceled)
        {
            Snackbar.Add("عضویت با موفقیت غیرفعال شد", Severity.Warning);
            await ApplyFilter();
        }
    }

    private async Task ExportToExcel()
    {
        try
        {
            var request = new GetAllClubMembershipsRequest
            {
                PageIndex = 1,
                PageSize = 1000,
                IsActive = _filterIsActive
            };

            var result = await ClubContract.GetAllClubMembershipsAsync(request);

            if (result?.Models == null || !result.Models.Any())
            {
                Snackbar.Add("داده‌ای برای خروجی وجود ندارد.", Severity.Info);
                return;
            }

            var sb = new StringBuilder();
            sb.AppendLine("شناسه,کاربر,نام کاربر,پکیج,کد فعال‌سازی,تاریخ فعال‌سازی,تاریخ انقضا,فعال,منقضی");

            foreach (var m in result.Models)
            {
                sb.AppendLine(string.Join(",",
                    m.Id,
                    m.UserId,
                    EscapeCsv(m.UserName),
                    EscapeCsv(m.PackageName),
                    EscapeCsv(m.ActivationCode),
                    m.ActivatedAt.ToDateTime().ToLocalTime().MiladiToJalaliWithTime(),
                    m.ExpiresAt.ToDateTime().ToLocalTime().MiladiToJalaliWithTime(),
                    m.IsActive ? "فعال" : "غیرفعال",
                    m.IsExpired ? "بله" : "خیر"));
            }

            var bytes = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(sb.ToString())).ToArray();
            var base64 = Convert.ToBase64String(bytes);
            var filename = $"club-members-{DateTime.Now:yyyyMMddHHmmss}.csv";

            await JsRuntime.InvokeVoidAsync("jsSaveAsFile", filename, base64);
            Snackbar.Add("خروجی Excel (CSV) آماده شد.", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در خروجی Excel: {ex.Message}", Severity.Error);
        }
    }

    private static string EscapeCsv(string value)
    {
        if (string.IsNullOrEmpty(value)) return "";
        if (value.Contains(',') || value.Contains('"') || value.Contains('\n'))
            return $"\"{value.Replace("\"", "\"\"")}\"";
        return value;
    }
}
