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

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

export const activityReportTemplate: 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: 'activitySummary',
        type: 'text',
        position: { x: 20, y: 50 },
        width: 170,
        height: 80,
        fontSize: 10,
      },
      {
        name: 'activityDetails',
        type: 'text',
        position: { x: 20, y: 140 },
        width: 170,
        height: 120,
        fontSize: 9,
      },
    ],
  ],
};

export function buildActivityInputs(
  data: ActivityData,
  portName?: string,
): Record<string, string>[] {
  const summaryLines = [
    `Activity Summary (${data.logs.length} events)`,
    '─────────────────────',
  ];

  const sortedSummary = Object.entries(data.summary).sort((a, b) => b[1] - a[1]);
  if (sortedSummary.length === 0) {
    summaryLines.push('No activity recorded in the selected period.');
  } else {
    for (const [key, cnt] of sortedSummary.slice(0, 15)) {
      summaryLines.push(`${key}: ${cnt}`);
    }
  }

  const detailLines = ['Recent Activity Log', '─────────────────────'];
  const recentLogs = data.logs.slice(0, 30);
  if (recentLogs.length === 0) {
    detailLines.push('No activity logs found.');
  } else {
    for (const log of recentLogs) {
      const date = new Date(log.createdAt).toLocaleDateString('en-GB');
      detailLines.push(
        `${date}  ${log.action}  ${log.entityType}${log.entityId ? ` (${log.entityId.slice(0, 8)}...)` : ''}`,
      );
    }
  }

  return [
    {
      reportTitle: 'Activity Report',
      portName: portName ?? 'Port Nimara',
      generatedAt: `Generated: ${new Date(data.generatedAt).toLocaleString('en-GB')}`,
      activitySummary: summaryLines.join('\n'),
      activityDetails: detailLines.join('\n'),
    },
  ];
}
