import {
  BarChart,
  DataTable,
  DocumentShell,
  KeyValueGrid,
  Section,
  type BarDatum,
} from '@/lib/pdf/brand-kit';
import { stageLabel } from '@/lib/constants';
import type { RevenueData } from '@/lib/services/report-generators';

export interface RevenueReportPdfProps {
  portName: string;
  logoBuffer: Buffer | null;
  data: RevenueData;
  dateFrom?: string;
  dateTo?: string;
  currency?: string;
}

const STAGE_ORDER = [
  'enquiry',
  'qualified',
  'nurturing',
  'eoi',
  'reservation',
  'deposit_paid',
  'contract',
];

function fmtAmount(n: number, currency: string): string {
  return `${currency} ${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

export function RevenueReportPdf({
  portName,
  logoBuffer,
  data,
  dateFrom,
  dateTo,
  currency = 'USD',
}: RevenueReportPdfProps) {
  const stages = [
    ...STAGE_ORDER.filter((s) => data.stageRevenue[s] !== undefined),
    ...Object.keys(data.stageRevenue).filter((s) => !STAGE_ORDER.includes(s)),
  ];
  const rows = stages.map((stage) => ({
    stage,
    amount: Number(data.stageRevenue[stage] ?? 0),
  }));
  const chartData: BarDatum[] = rows.map((r) => ({ label: stageLabel(r.stage), value: r.amount }));
  const totalCompleted = Number(data.totalCompleted);
  const totalForecast = Number(data.totalForecast);
  const subtotal = rows.reduce((s, r) => s + r.amount, 0);
  const meta = dateFrom || dateTo ? `Range: ${dateFrom ?? '-'} → ${dateTo ?? 'today'}` : 'All time';

  return (
    <DocumentShell
      portName={portName}
      docTitle="Revenue Report"
      docMeta={meta}
      logoBuffer={logoBuffer}
    >
      <Section
        title="Revenue summary"
        subtitle="Completed = money changed hands. Forecast = active pipeline weighted by stage probability."
      >
        <KeyValueGrid
          rows={[
            { label: 'Completed revenue (won)', value: fmtAmount(totalCompleted, currency) },
            {
              label: 'Forecast revenue (pipeline-weighted)',
              value: fmtAmount(totalForecast, currency),
            },
            { label: 'Pipeline value (open, gross)', value: fmtAmount(subtotal, currency) },
            { label: 'Currency', value: currency },
          ]}
        />
      </Section>

      <Section
        title="Revenue by stage"
        subtitle="Sum of expected berth value at each pipeline stage."
      >
        <BarChart data={chartData} height={220} showValues />
      </Section>

      <Section title="Breakdown">
        <DataTable<{ stage: string; amount: number }>
          columns={[
            { header: 'Stage', flex: 3, render: (r) => stageLabel(r.stage) },
            {
              header: 'Amount',
              flex: 2,
              align: 'right',
              render: (r) => fmtAmount(r.amount, currency),
            },
          ]}
          rows={rows}
          totals={['Total', fmtAmount(subtotal, currency)]}
          emptyMessage="No revenue data."
        />
      </Section>
    </DocumentShell>
  );
}
