import { View, Text } from '@react-pdf/renderer';

import { stageLabel } from '@/lib/constants';
import { BrandedReportDocument } from './branded-document';
import { ReportTable } from './report-table';
import { makeReportStyles } from './styles';
import type { InterestListReportConfig, ReportBranding } from './types';
import type { InterestReportData } from '@/lib/services/list-report-data.service';

interface Props {
  title: string;
  subtitle?: string;
  branding: ReportBranding;
  generatedAt: string;
  config: InterestListReportConfig;
  data: InterestReportData;
}

const DEFAULT_COLUMNS: ReadonlyArray<{ key: string; label: string; widthPct: number }> = [
  { key: 'clientName', label: 'Client', widthPct: 32 },
  { key: 'primaryMooring', label: 'Mooring', widthPct: 13 },
  { key: 'pipelineStage', label: 'Stage', widthPct: 22 },
  { key: 'source', label: 'Source', widthPct: 15 },
  { key: 'outcome', label: 'Outcome', widthPct: 8 },
  { key: 'createdAt', label: 'Created', widthPct: 10 },
];

/**
 * Interest pipeline export. Rows are grouped within the underlying
 * query by stage (sort by updatedAt desc, but the rep can re-sort
 * the printed PDF mentally via the Stage column).
 *
 * `outcome` is rendered with a single-letter shorthand (W / L / -)
 * so the column doesn't dominate the row width.
 */
export function InterestListReport({
  title,
  subtitle,
  branding,
  generatedAt,
  config,
  data,
}: Props) {
  const styles = makeReportStyles(branding);
  const columns = pickColumns(config.columns);
  const cappedNotice = data.capHit
    ? `Showing the most recent ${data.rows.length} of ${data.total.toLocaleString()} matching interests.`
    : `${data.rows.length} ${data.rows.length === 1 ? 'interest' : 'interests'}`;

  return (
    <BrandedReportDocument
      branding={branding}
      title={title}
      subtitle={subtitle ?? 'Interest pipeline'}
      generatedAt={generatedAt}
    >
      <View>
        <Text style={styles.sectionSubtitle} minPresenceAhead={80}>
          {cappedNotice}
        </Text>
        <ReportTable
          styles={styles}
          headers={columns.map((c) => c.label)}
          widths={columns.map((c) => c.widthPct)}
          rows={data.rows.map((r) => columns.map((c) => formatCell(c.key, r)))}
        />
      </View>
    </BrandedReportDocument>
  );
}

function pickColumns(override?: string[]) {
  if (!override || override.length === 0) return [...DEFAULT_COLUMNS];
  const map = new Map(DEFAULT_COLUMNS.map((c) => [c.key, c]));
  return override.flatMap((k) => (map.has(k) ? [map.get(k)!] : []));
}

function formatCell(key: string, row: InterestReportData['rows'][number]): string {
  switch (key) {
    case 'clientName':
      return row.clientName ?? '';
    case 'primaryMooring':
      return row.primaryMooring ?? '';
    case 'pipelineStage':
      return stageLabel(row.pipelineStage);
    case 'source':
      return row.source ?? '';
    case 'outcome':
      return row.outcome === 'won' ? 'W' : row.outcome === 'lost' ? 'L' : '-';
    case 'createdAt':
      return new Date(row.createdAt).toLocaleDateString('en-GB');
    default:
      return '';
  }
}
