using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MudBlazor;
using System.Text;
using DateTimeConverterCL;
using CMSMicroservice.Protobuf.Protos.ManualPayment;

namespace BackOffice.Pages.Payment;

public partial class ManualPayments
{
    [Inject] public IJSRuntime JsRuntime { get; set; } = default!;

    private async Task ExportToExcel()
    {
        try
        {
            var request = new GetAllManualPaymentsRequest
            {
                PageNumber = 1,
                PageSize = 1000
            };

            if (_userIdFilter.HasValue)
                request.UserId = _userIdFilter.Value;
            if (_statusFilter.HasValue)
                request.Status = _statusFilter.Value;
            if (_typeFilter.HasValue)
                request.Type = _typeFilter.Value;

            var response = await ManualPaymentClient.GetAllManualPaymentsAsync(request);

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

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

            foreach (var m in response.Models)
            {
                sb.AppendLine(string.Join(",",
                    m.Id,
                    m.UserId,
                    EscapeCsv(m.UserFullName),
                    EscapeCsv(m.PackageName ?? "-"),
                    m.Amount.ToString("N0"),
                    EscapeCsv(GetTypeText((int)m.Type)),
                    EscapeCsv(GetStatusText((int)m.Status)),
                    m.Created?.ToDateTime().ToLocalTime().MiladiToJalaliWithTime() ?? "-"));
            }

            var bytes = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(sb.ToString())).ToArray();
            var base64 = Convert.ToBase64String(bytes);
            var filename = $"manual-payments-{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;
    }
}
