using CMSMicroservice.Protobuf.Protos.User;
using BackOffice.Common.BaseComponents;
using BackOffice.Pages.User.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MudBlazor;
using System.Text;
using DateTimeConverterCL;
using DataModel = CMSMicroservice.Protobuf.Protos.User.GetAllUserByFilterResponseModel;

namespace BackOffice.Pages.User;
public partial class UserMainPage
{
    [Inject] public UserContract.UserContractClient UserContract { get; set; }
    [Inject] public IJSRuntime JsRuntime { get; set; }
    private bool _isLoading = true;
    private MudDataGrid<DataModel> _gridData;
    BasePageComponent _basePage;
    private GetAllUserByFilterRequest _request = new() { Filter = new() };
    private async Task<GridData<DataModel>> ServerReload(GridState<DataModel> state)
    {
        _request.Filter ??= new();
        _request.PaginationState ??= new();
        _request.PaginationState.PageNumber = state.Page + 1;
        _request.PaginationState.PageSize = state.PageSize;

        var result = await UserContract.GetAllUserByFilterAsync(_request);
        if (result != null && result.Models != null && result.Models.Any())
        {
            return new GridData<DataModel>() { Items = result.Models.ToList(), TotalItems = (int)result.MetaData.TotalCount };
        }

        return new GridData<DataModel>();
    }
    private async Task OnDelete(DataModel model)
    {
        var options = new DialogOptions { CloseOnEscapeKey = true, MaxWidth = MaxWidth.Small };
        bool? result = await DialogService.ShowMessageBox(
            "اخطار",
            $"آیا از حذف کاربر «{model.FirstName} {model.LastName}» مطمئن هستید؟",
            yesText: "حذف", cancelText: "لغو",
            options: options);
        if (result != null && result.Value)
        {
            await UserContract.DeleteUserAsync(new()
            {
                Id = model.Id
            });
            ReLoadData();
        }
        StateHasChanged();
    }
    public async void ReLoadData()
    {
        if (_gridData != null)
            await _gridData.ReloadServerData();
    }
    public async Task OnclickUserRoleDialog(long userid)
    {
        var dialog = await DialogService.ShowAsync<UserRoleDialog>($"نقش های کاربر", new DialogParameters<UserRoleDialog>() { { x => x.UserId, userid } }, new DialogOptions() { CloseButton = true, FullWidth = true, MaxWidth = MaxWidth.Small });
        var result = await dialog.Result;
        if (!result.Canceled)
        {
            ReLoadData();
            Snackbar.Add("عملیات با موفقیت انجام شد", Severity.Success);
        }
    }
    public async Task OnFilterSubmit()
    {
        _basePage.IsFiltered = true;
        StateHasChanged();
        ReLoadData();
    }

    public async Task OnFilterCleared()
    {
        _basePage.IsFiltered = false;
        StateHasChanged();
        _request = new() { Filter = new() { } };
        ReLoadData();
    }

    private async Task ExportToExcel()
    {
        try
        {
            var exportRequest = new GetAllUserByFilterRequest
            {
                Filter = _request.Filter?.Clone() ?? new(),
                PaginationState = new() { PageNumber = 1, PageSize = 1000 }
            };

            var result = await UserContract.GetAllUserByFilterAsync(exportRequest);

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

            var sb = new StringBuilder();
            sb.AppendLine("شناسه,موبایل,نام,نام خانوادگی,کدملی");

            foreach (var u in result.Models)
            {
                sb.AppendLine(string.Join(",",
                    u.Id,
                    EscapeCsv(u.Mobile),
                    EscapeCsv(u.FirstName),
                    EscapeCsv(u.LastName),
                    EscapeCsv(u.NationalCode)));
            }

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