using GestionIntegral.Api.Dtos.Reportes.ViewModels;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System.Globalization;
using System.Linq;

namespace GestionIntegral.Api.Controllers.Reportes.PdfTemplates
{
  public class CuentasDistribuidorDocument : IDocument
  {
    public CuentasDistribuidorViewModel Model { get; }
    private static readonly CultureInfo CultureAr = new CultureInfo("es-AR", false)
    {
      NumberFormat = { CurrencySymbol = "$" }
    };

    public CuentasDistribuidorDocument(CuentasDistribuidorViewModel model)
    {
      Model = model;
    }

    public DocumentMetadata GetMetadata() => DocumentMetadata.Default;
    public DocumentSettings GetSettings() => DocumentSettings.Default;

    public void Compose(IDocumentContainer container)
    {
      container.Page(page =>
      {
        page.Margin(1, Unit.Centimetre);
        page.DefaultTextStyle(x => x.FontFamily("Arial").FontSize(9));
        page.Header().Element(ComposeHeader);
        page.Content().Element(ComposeContent);
        page.Footer().AlignCenter().Text(x => { x.Span("Página "); x.CurrentPageNumber(); x.Span(" de "); x.TotalPages(); });
      });
    }

    void ComposeHeader(IContainer container)
    {
      container.Column(column =>
      {
        column.Item().Row(row =>
              {
                row.RelativeItem().Text($"Fecha de Reporte   {Model.FechaReporte}");
                row.RelativeItem().AlignCenter().Text("Cuenta De Distribuidor").SemiBold().FontSize(14);
                row.RelativeItem();
              });

        column.Item().AlignCenter().Text(Model.NombreDistribuidor).FontSize(12);

        column.Item().PaddingTop(2, Unit.Millimetre).Row(row =>
              {
                row.RelativeItem(2);
                row.RelativeItem(8).AlignCenter().Text(text =>
                      {
                        text.Span("Fecha Consultada: Desde ").SemiBold();
                        text.Span(Model.FechaDesde);
                        text.Span(" Hasta ").SemiBold();
                        text.Span(Model.FechaHasta);
                      });
                row.RelativeItem(2);
              });
      });
    }

    void ComposeContent(IContainer container)
    {
      container.PaddingTop(1, Unit.Centimetre).Column(column =>
      {
        column.Spacing(20);

        if (Model.Movimientos.Any()) column.Item().Element(ComposeMovimientosTable);
        if (Model.Pagos.Any()) column.Item().Element(ComposePagosTable);
        if (Model.DebitosCreditos.Any()) column.Item().Element(ComposeDebCredTable);

        column.Item().Element(ComposeResumenPeriodo);
      });
    }

    void ComposeMovimientosTable(IContainer container)
    {
      container.Column(column =>
      {
        column.Item().PaddingBottom(5).Text("Movimientos").SemiBold().FontSize(11);
        column.Item().Table(table =>
              {
                table.ColumnsDefinition(columns =>
                      {
                        columns.ConstantColumn(60);
                        columns.RelativeColumn(2);
                        columns.ConstantColumn(50);
                        columns.ConstantColumn(50);
                        columns.RelativeColumn(1.5f);
                        columns.RelativeColumn(1.5f);
                        columns.RelativeColumn(2);
                      });

                table.Header(header =>
                      {
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Fecha");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Publicacion");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Remito");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignCenter().Text("Cantidad");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Debe");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Haber");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Saldo");
                      });

                // Fila Saldo Inicial al inicio de la primera tabla — ancla del acumulado
                table.Cell().ColumnSpan(6).Border(1).Padding(2).Text(t => t.Span("Saldo Inicial").SemiBold());
                table.Cell().Border(1).Padding(2).AlignRight().Text(t => t.Span(Model.SaldoInicial.ToString("C", CultureAr)).SemiBold());

                decimal saldoAcumulado = Model.SaldoInicial;
                foreach (var item in Model.Movimientos.OrderBy(m => m.Fecha))
                {
                  saldoAcumulado += (item.Debe - item.Haber);
                  table.Cell().Border(1).Padding(2).Text(item.Fecha.ToString("dd/MM/yyyy"));
                  table.Cell().Border(1).Padding(2).Text(item.Publicacion);
                  table.Cell().Border(1).Padding(2).Text(item.Remito);
                  table.Cell().Border(1).Padding(2).AlignCenter().Text(item.Cantidad.ToString("N0"));
                  table.Cell().Border(1).Padding(2).AlignRight().Text(item.Debe.ToString("C", CultureAr));
                  table.Cell().Border(1).Padding(2).AlignRight().Text(item.Haber.ToString("C", CultureAr));
                  table.Cell().Border(1).Padding(2).AlignRight().Text(saldoAcumulado.ToString("C", CultureAr));
                }

                table.Cell().ColumnSpan(4).Border(1).AlignRight().Padding(2).Text(t => t.Span("Totales").SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(Model.Movimientos.Sum(x => x.Debe).ToString("C", CultureAr)).SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(Model.Movimientos.Sum(x => x.Haber).ToString("C", CultureAr)).SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(saldoAcumulado.ToString("C", CultureAr)).SemiBold());
              });
      });
    }

    void ComposePagosTable(IContainer container)
    {
      container.Column(column =>
      {
        column.Item().PaddingBottom(5).Text("Pagos").SemiBold().FontSize(12);
        column.Item().Table(table =>
              {
                table.ColumnsDefinition(columns =>
                      {
                        columns.ConstantColumn(60);
                        columns.RelativeColumn(1.5f);
                        columns.ConstantColumn(50);
                        columns.RelativeColumn(1.5f);
                        columns.RelativeColumn(1.5f);
                        columns.RelativeColumn(1.5f);
                        columns.RelativeColumn(2);
                      });

                table.Header(header =>
                      {
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Fecha");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Recibo");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Tipo");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Debe");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Haber");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Saldo");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Detalle");
                      });

                decimal saldoAcumulado = Model.SaldoInicial + Model.TotalMovimientos;
                foreach (var item in Model.Pagos.OrderBy(p => p.Fecha).ThenBy(p => p.Recibo))
                {
                  saldoAcumulado += (item.Debe - item.Haber);
                  table.Cell().Border(1).Padding(2).Text(item.Fecha.ToString("dd/MM/yyyy"));
                  table.Cell().Border(1).Padding(2).Text(item.Recibo.ToString());
                  table.Cell().Border(1).Padding(2).Text(item.Tipo);
                  table.Cell().Border(1).Padding(2).AlignRight().Text(item.Debe.ToString("C", CultureAr));
                  table.Cell().Border(1).Padding(2).AlignRight().Text(item.Haber.ToString("C", CultureAr));
                  table.Cell().Border(1).Padding(2).AlignRight().Text(saldoAcumulado.ToString("C", CultureAr));
                  table.Cell().Border(1).Padding(2).Text(item.Detalle);
                }

                table.Cell().ColumnSpan(3).Border(1).AlignRight().Padding(2).Text(t => t.Span("Totales").SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(Model.Pagos.Sum(x => x.Debe).ToString("C", CultureAr)).SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(Model.Pagos.Sum(x => x.Haber).ToString("C", CultureAr)).SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(saldoAcumulado.ToString("C", CultureAr)).SemiBold());
                table.Cell().Border(1);
              });
      });
    }

    void ComposeDebCredTable(IContainer container)
    {
      container.Column(column =>
      {
        column.Item().PaddingBottom(5).Text("Débitos / Créditos").SemiBold().FontSize(12);
        column.Item().Table(table =>
              {
                table.ColumnsDefinition(columns =>
                      {
                        columns.ConstantColumn(65);
                        columns.RelativeColumn(2);
                        columns.RelativeColumn(1);
                        columns.RelativeColumn(1);
                        columns.RelativeColumn(2);
                      });

                table.Header(header =>
                      {
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Fecha");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).Text("Referencia");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Debe");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Haber");
                        header.Cell().Border(1).Background(Colors.Grey.Lighten3).Padding(2).AlignRight().Text("Saldo");
                      });

                decimal saldoAcumulado = Model.SaldoInicial + Model.TotalMovimientos + Model.TotalPagos;
                foreach (var item in Model.DebitosCreditos.OrderBy(dc => dc.Fecha))
                {
                  saldoAcumulado += (item.Debe - item.Haber);
                  table.Cell().Border(1).Padding(2).Text(item.Fecha.ToString("dd/MM/yyyy"));
                  table.Cell().Border(1).Padding(2).Text(item.Referencia);
                  table.Cell().Border(1).Padding(2).AlignRight().Text(item.Debe.ToString("C", CultureAr));
                  table.Cell().Border(1).Padding(2).AlignRight().Text(item.Haber.ToString("C", CultureAr));
                  table.Cell().Border(1).Padding(2).AlignRight().Text(saldoAcumulado.ToString("C", CultureAr));
                }

                table.Cell().ColumnSpan(2).Border(1).AlignRight().Padding(2).Text(t => t.Span("Totales").SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(Model.DebitosCreditos.Sum(x => x.Debe).ToString("C", CultureAr)).SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(Model.DebitosCreditos.Sum(x => x.Haber).ToString("C", CultureAr)).SemiBold());
                table.Cell().Border(1).AlignRight().Padding(2).Text(t => t.Span(saldoAcumulado.ToString("C", CultureAr)).SemiBold());
              });
      });
    }

    void ComposeResumenPeriodo(IContainer container)
    {
      container.PaddingTop(5, Unit.Millimetre).AlignLeft().Column(column =>
      {
        column.Item().Border(1).Padding(5).Width(300, Unit.Point).Column(col =>
      {
            col.Spacing(5);
            col.Item().Text("Datos totales del periodo consultado").SemiBold();
            Action<RowDescriptor, string, decimal> AddResumenRow = (row, label, value) =>
          {
                row.RelativeItem().Text(label);
                row.ConstantItem(120).AlignRight().Text(value.ToString("C", CultureAr));
              };
            col.Item().Row(row => AddResumenRow(row, "Saldo Inicial", Model.SaldoInicial));
            col.Item().Row(row => AddResumenRow(row, "Movimientos", Model.TotalMovimientos));
            col.Item().Row(row => AddResumenRow(row, "Débitos/Créditos", Model.TotalDebitosCreditos));
            col.Item().Row(row => AddResumenRow(row, "Pagos", Model.TotalPagos));
            col.Item().BorderTop(1.5f).BorderColor(Colors.Black).PaddingTop(5).Row(row =>
          {
                row.RelativeItem().Text("Saldo Final").SemiBold();
                row.ConstantItem(120).AlignRight().Text(t => t.Span(Model.SaldoFinal.ToString("C", CultureAr)).SemiBold());
              });
          });
      });
    }
  }
}
