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

export interface PipelineReportPdfProps {
  portName: string;
  logoBuffer: Buffer | null;
  data: PipelineData;
}

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

interface TopInterestRow {
  id: string;
  clientId: string;
  pipelineStage: string;
  berthPrice: string | null;
}

export function PipelineReportPdf({ portName, logoBuffer, data }: PipelineReportPdfProps) {
  const funnel: FunnelDatum[] = FUNNEL_STAGES.map((stage) => ({
    label: stageLabel(stage),
    value: data.stageCounts[stage] ?? 0,
  })).filter((d) => d.value > 0);

  const totalInterests = Object.values(data.stageCounts).reduce((sum, n) => sum + n, 0);
  const completed = data.stageCounts.completed ?? 0;
  const cancelled = data.stageCounts.cancelled ?? 0;
  const winRate = totalInterests > 0 ? Math.round((completed / totalInterests) * 100) : 0;
  const topStage = Object.entries(data.stageCounts).sort((a, b) => b[1] - a[1])[0];

  return (
    <DocumentShell portName={portName} docTitle="Pipeline Report" logoBuffer={logoBuffer}>
      <Section title="Summary">
        <KeyValueGrid
          rows={[
            { label: 'Total interests', value: totalInterests.toLocaleString() },
            { label: 'Win rate', value: `${winRate}%` },
            { label: 'Completed', value: completed.toLocaleString() },
            {
              label: 'Top stage',
              value: topStage ? `${stageLabel(topStage[0])} (${topStage[1]})` : '-',
            },
            { label: 'Cancelled / Lost', value: cancelled.toLocaleString() },
          ]}
        />
      </Section>

      <Section title="Pipeline funnel" subtitle="Interests at each stage of the pipeline.">
        <FunnelChart data={funnel} height={280} />
      </Section>

      <Section title="Top interests" subtitle="Highest-value open interests, by berth price.">
        <DataTable<TopInterestRow>
          columns={[
            { header: 'Stage', flex: 2, render: (r) => stageLabel(r.pipelineStage) },
            { header: 'Client', flex: 2, render: (r) => r.clientId.slice(0, 8) + '…' },
            {
              header: 'Berth price',
              flex: 2,
              align: 'right',
              render: (r) => (r.berthPrice ? Number(r.berthPrice).toLocaleString() : '-'),
            },
          ]}
          rows={data.topInterests}
          emptyMessage="No open interests."
        />
      </Section>
    </DocumentShell>
  );
}
