@page "/contracts"
@attribute [Authorize(Roles = "Administrator")]

@using CMSMicroservice.Protobuf.Protos.UserContract
@using BackOffice.Pages.AutoComplete
@inject Microsoft.JSInterop.IJSRuntime JsRuntime
@inject UserContractContract.UserContractContractClient UserContractClient

<div>
    <MudText Typo="Typo.h5" Class="mb-3">قراردادهای کاربران</MudText>

    <MudDataGrid T="GetAllUserContractByFilterResponseModel" @ref="_grid"
                 ServerData="LoadContracts"
                 Hover="true" Dense="true"
                 Height="calc(100vh - 240px)">
        <ToolBarContent>
            <MudStack Row="true" Spacing="2" AlignItems="AlignItems.Center">
                <UserAutoComplete Label="جستجوی کاربر" @bind-SelectedUserId="_filterUserId" />
                <MudButton Variant="Variant.Filled" Color="Color.Primary"
                           StartIcon="@Icons.Material.Filled.Search"
                           OnClick="ApplyFilter">جستجو</MudButton>
            </MudStack>
        </ToolBarContent>
        <Columns>
            <PropertyColumn Property="x => x.Id" Title="شناسه" />
            <PropertyColumn Property="x => x.UserId" Title="شناسه کاربر" />
            <PropertyColumn Property="x => x.ContractId" Title="شناسه قرارداد" />
            <PropertyColumn Property="x => x.SignGuid" Title="کد امضا" />
            <TemplateColumn Title="فایل PDF" Sortable="false">
                <CellTemplate>
                    @if (!string.IsNullOrWhiteSpace(context.Item.SignedPdfFile))
                    {
                        <MudButton Variant="Variant.Text" Color="Color.Primary" Size="Size.Small"
                                   StartIcon="@Icons.Material.Filled.PictureAsPdf"
                                   OnClick="@(() => DownloadPdf(context.Item))">
                            دانلود PDF
                        </MudButton>
                    }
                    else
                    {
                        <MudText Typo="Typo.caption" Color="Color.Secondary">بدون فایل</MudText>
                    }
                </CellTemplate>
            </TemplateColumn>
            <TemplateColumn Title="عملیات" Sortable="false">
                <CellTemplate>
                    <MudTooltip Text="جزئیات">
                        <MudIconButton Icon="@Icons.Material.Filled.Visibility"
                                       Size="Size.Small" Color="Color.Info"
                                       OnClick="@(() => ViewDetails(context.Item))" />
                    </MudTooltip>
                </CellTemplate>
            </TemplateColumn>
        </Columns>
        <NoRecordsContent>
            <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="my-4">قراردادی یافت نشد.</MudAlert>
        </NoRecordsContent>
        <PagerContent>
            <MudDataGridPager T="GetAllUserContractByFilterResponseModel" PageSizeOptions="@(new int[] { 20, 50, 100 })"
                              InfoFormat="سطر {first_item} تا {last_item} از {all_items}"
                              RowsPerPageString="تعداد در صفحه" />
        </PagerContent>
    </MudDataGrid>
</div>

@code {
    private MudDataGrid<GetAllUserContractByFilterResponseModel>? _grid;
    private long? _filterUserId;

    private async Task<GridData<GetAllUserContractByFilterResponseModel>> LoadContracts(GridState<GetAllUserContractByFilterResponseModel> state)
    {
        try
        {
            var request = new GetAllUserContractByFilterRequest
            {
                PaginationState = new() { PageNumber = state.Page + 1, PageSize = state.PageSize },
                Filter = new GetAllUserContractByFilterFilter()
            };

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

            var result = await UserContractClient.GetAllUserContractByFilterAsync(request);
            return new GridData<GetAllUserContractByFilterResponseModel>
            {
                Items = result?.Models?.ToList() ?? new(),
                TotalItems = (int)(result?.MetaData?.TotalCount ?? 0)
            };
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
            return new GridData<GetAllUserContractByFilterResponseModel>();
        }
    }

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

    private async Task ViewDetails(GetAllUserContractByFilterResponseModel contract)
    {
        var parameters = new DialogParameters
        {
            ["Contract"] = contract
        };
        var options = new DialogOptions { MaxWidth = MaxWidth.Small, FullWidth = true };
        await DialogService.ShowAsync<ContractDetailsDialog>("جزئیات قرارداد", parameters, options);
    }

    private async Task DownloadPdf(GetAllUserContractByFilterResponseModel contract)
    {
        if (!string.IsNullOrWhiteSpace(contract.SignedPdfFile))
        {
            var title = $"قرارداد کاربر {contract.UserId}";
            await JsRuntime.InvokeVoidAsync("jsHtmlToPdf", contract.SignedPdfFile, title);
        }
    }
}
