using CMSMicroservice.Protobuf.Protos.User;
using BackOffice.Common.BaseComponents;
using BackOffice.Common.Utilities;
using BackOffice.Pages.User.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MudBlazor;
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 filter = _request.Filter?.Clone() ?? new();
            var all = new List<DataModel>();
            const int pageSize = 200;
            var page = 1;

            while (page <= 500)
            {
                var result = await UserContract.GetAllUserByFilterAsync(new GetAllUserByFilterRequest
                {
                    Filter = filter,
                    PaginationState = new() { PageNumber = page, PageSize = pageSize }
                });

                var batch = result?.Models?.ToList() ?? new();
                if (batch.Count == 0)
                    break;

                all.AddRange(batch);

                var hasNext = result?.MetaData?.HasNext == true;
                if (!hasNext || batch.Count < pageSize)
                    break;

                page++;
            }

            if (all.Count == 0)
            {
                Snackbar.Add("داده‌ای برای خروجی وجود ندارد.", Severity.Info);
                return;
            }

            var headers = new[]
            {
                "شناسه", "موبایل", "نام", "نام خانوادگی", "کدملی",
                "آدرس پیش‌فرض", "کدپستی پیش‌فرض"
            };

            var rows = all.Select(u => new object?[]
            {
                u.Id,
                u.Mobile,
                u.FirstName,
                u.LastName,
                u.NationalCode,
                u.DefaultAddress,
                u.DefaultPostalCode
            });

            var filename = $"users-{DateTime.Now:yyyyMMddHHmmss}.xls";
            await JsRuntime.InvokeVoidAsync("jsSaveAsFile", filename,
                CsvExportHelper.ToExcelXmlBase64("کاربران", headers, rows));
            Snackbar.Add($"خروجی Excel آماده شد ({all.Count} کاربر).", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در خروجی Excel: {ex.Message}", Severity.Error);
        }
    }
}
