@using AyCode.Blazor.Components.Components.Grids
@using AyCode.Blazor.Components.Components
@using DevExpress.Blazor
@using FruitBank.Common.Entities
@using System.IO
@inject IJSRuntime JS

<MgGridInfoPanel OnDataItemChanged="OnDataItemChangedAsync">
	@* <HeaderTemplate Context="ctx">
        <div class="dxbl-grid-header-panel px-3 py-2 border-bottom d-flex align-items-center">
            <span class="me-2">??</span>
            <span class="fw-semibold">Szállítólevél részletei</span>
        </div>
    </HeaderTemplate> *@

	@* <BeforeColumnsTemplate Context="ctx">
        @if (ctx.DataItem is ShippingDocument doc)
        {
            <div class="alert alert-info mb-2 py-1 px-2 small">
                <strong>Partner:</strong> @doc.Partner?.Name
            </div>
        }
    </BeforeColumnsTemplate> *@

	<AfterColumnsTemplate Context="ctx">
		@if (ctx.DataItem is not ShippingDocument && ctx.DataItem is not ShippingItem) return;

		@if (ctx is { DataItem: ShippingDocument doc, IsEditMode: false })
		{
			<table class="table table-sm table-bordered table-striped" style="margin-top: 35px;">
				<colgroup>
					<col style="width: auto;" />
					<col style="width: 25%;" />
					<col style="width: 65px;" />
					<col style="width: 65px;" />
					<col style="width: 65px;" />
					<col style="width: 65px;" />
				</colgroup>
				<thead class="table-light">
					<tr>
						<th>Név a dokumentumon</th>
						<th>Termék neve</th>
						<th>Rakl.</th>
						<th class="text-end">Menny.</th>
						<th class="text-end">Net.súly</th>
						<th class="text-end">Br.súly</th>
					</tr>
				</thead>
				<tbody>
					@foreach (var shippingItem in doc.ShippingItems)
					{
						<tr>
							<td>@shippingItem.NameOnDocument</td>
							<td>@shippingItem.ProductName</td>
							<td class="text-end">@shippingItem.PalletsOnDocument</td>
							<td class="text-end">@shippingItem.QuantityOnDocument</td>
							<td class="text-end">@shippingItem.NetWeightOnDocument</td>
							<td class="text-end">@shippingItem.GrossWeightOnDocument</td>
						</tr>
					}
				</tbody>
				<tfoot class="table-light fw-bold">
					<tr>
						<td>TOTAL:</td>
						<td></td>
						<td class="text-end">@doc.ShippingItems.Sum(x => x.PalletsOnDocument)</td>
						<td class="text-end">@doc.ShippingItems.Sum(x => x.QuantityOnDocument)</td>
						<td class="text-end">@double.Round(doc.ShippingItems.Sum(x => x.NetWeightOnDocument), 1)</td>
						<td class="text-end">@double.Round(doc.ShippingItems.Sum(x => x.GrossWeightOnDocument), 1)</td>
					</tr>
				</tfoot>
			</table>
		}

@* 		<MgLazyLoadContent @ref="_lazyContentRef"
						   MinHeight="800px"
						   RootMargin="50px"
						   OnContentVisible="OnPdfContainerVisibleAsync"
						   ContainerStyle="margin-top: 30px;">
			<div id="pdfContainer" style="width: 100%; height: 800px; overflow-y: auto;">
			</div>
		</MgLazyLoadContent>*@

 	</AfterColumnsTemplate>

	@* <FooterTemplate Context="ctx">
        <div class="p-2 border-top d-flex gap-2">
            <DxButton Text="Nyomtatás" IconCssClass="dx-icon dx-icon-print" RenderStyle="ButtonRenderStyle.Light" />
            <DxButton Text="Export" IconCssClass="dx-icon dx-icon-export" RenderStyle="ButtonRenderStyle.Light" />
        </div>
    </FooterTemplate> *@
</MgGridInfoPanel>

@code
{
	private readonly string[] _pdfFiles =
	[
	"1_Albaran_AH25007715.pdf",
		"2_BANK  FRA.pdf",
		"3_BP-30M35_20251113_163816.pdf"
	];

	private MgLazyLoadContent? _lazyContentRef;
	private string? _currentPdfToRender;
	private string _randomPdf;

	protected override void OnInitialized()
	{
		base.OnInitialized();
	}

	private async Task OnDataItemChangedAsync(object? dataItem)
	{
		if (dataItem is not ShippingDocument && dataItem is not ShippingItem) return;

		ShippingDocument? shippingDocument = null;

		if (dataItem is ShippingItem shippingItem) shippingDocument = shippingItem.ShippingDocument;
		else shippingDocument = dataItem as ShippingDocument;

		if (shippingDocument == null) return;

		if (_lazyContentRef != null && shippingDocument.ShippingDocumentToFiles?.Count > 0)
		{
			// Store the PDF to render
			_randomPdf = _pdfFiles[Random.Shared.Next(_pdfFiles.Length)];
			_currentPdfToRender = $"_content/FruitBankHybrid.Shared/uploads/{_randomPdf}";

			// If MgLazyLoadContent is already visible, render the PDF immediately
			if (_lazyContentRef is { IsVisible: true })
			{
				await _lazyContentRef.TriggerContentVisibleAsync();
			}
		}
	}

	private async Task OnPdfContainerVisibleAsync()
	{
		// Render PDF when container becomes visible OR when data changes
		if (!string.IsNullOrEmpty(_currentPdfToRender))
		{
			var pdfUrls = new[] { _currentPdfToRender };
			await JS.InvokeVoidAsync("pdfViewer.renderPdfs", "pdfContainer", pdfUrls);
		}
	}
}
