import type { Template } from '@pdfme/common';

import type { RevenueData } from '@/lib/services/report-generators';

export const revenueReportTemplate: Template = {
  basePdf: 'BLANK_PDF' as unknown as string,
  schemas: [
    [
      {
        name: 'reportTitle',
        type: 'text',
        position: { x: 20, y: 15 },
        width: 170,
        height: 12,
        fontSize: 20,
      },
      {
        name: 'portName',
        type: 'text',
        position: { x: 20, y: 30 },
        width: 130,
        height: 8,
        fontSize: 11,
      },
      {
        name: 'generatedAt',
        type: 'text',
        position: { x: 140, y: 30 },
        width: 50,
        height: 8,
        fontSize: 9,
      },
      {
        name: 'revenueBreakdown',
        type: 'text',
        position: { x: 20, y: 50 },
        width: 170,
        height: 120,
        fontSize: 10,
      },
      {
        name: 'totalText',
        type: 'text',
        position: { x: 20, y: 180 },
        width: 170,
        height: 20,
        fontSize: 12,
      },
    ],
  ],
};

export function buildRevenueInputs(
  data: RevenueData,
  portName?: string,
): Record<string, string>[] {
  const stageOrder = [
    'open',
    'details_sent',
    'in_communication',
    'visited',
    'signed_eoi_nda',
    'deposit_10pct',
    'contract',
    'completed',
  ];

  const breakdownLines = ['Revenue by Pipeline Stage', '─────────────────────'];

  const orderedStages = [
    ...stageOrder.filter((s) => data.stageRevenue[s] !== undefined),
    ...Object.keys(data.stageRevenue).filter((s) => !stageOrder.includes(s)),
  ];

  if (orderedStages.length === 0) {
    breakdownLines.push('No revenue data available.');
  } else {
    for (const stage of orderedStages) {
      const label = stage.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
      const amount = Number(data.stageRevenue[stage] ?? 0).toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
      breakdownLines.push(`${label}: ${amount}`);
    }
  }

  const totalCompleted = Number(data.totalCompleted).toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });

  return [
    {
      reportTitle: 'Revenue Report',
      portName: portName ?? 'Port Nimara',
      generatedAt: `Generated: ${new Date(data.generatedAt).toLocaleString('en-GB')}`,
      revenueBreakdown: breakdownLines.join('\n'),
      totalText: `TOTAL COMPLETED REVENUE: ${totalCompleted}`,
    },
  ];
}
