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

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

interface Props {
  title: string;
  subtitle?: string;
  branding: ReportBranding;
  generatedAt: string;
  config: ClientListReportConfig;
  data: ClientReportData;
}

const DEFAULT_COLUMNS: ReadonlyArray<{ key: string; label: string; widthPct: number }> = [
  { key: 'fullName', label: 'Name', widthPct: 30 },
  { key: 'primaryEmail', label: 'Email', widthPct: 25 },
  { key: 'primaryPhone', label: 'Phone', widthPct: 15 },
  { key: 'source', label: 'Source', widthPct: 12 },
  { key: 'nationality', label: 'Country', widthPct: 8 },
  { key: 'createdAt', label: 'Created', widthPct: 10 },
];

/**
 * Filtered clients list report. Columns can be subset via
 * `config.columns`; default set is the rep-facing subset most useful
 * on a printed report (skip internal IDs / metadata fields).
 */
export function ClientListReport({ 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 clients.`
    : `${data.rows.length} ${data.rows.length === 1 ? 'client' : 'clients'}`;

  return (
    <BrandedReportDocument
      branding={branding}
      title={title}
      subtitle={subtitle ?? 'Client list'}
      generatedAt={generatedAt}
    >
      <View>
        {/* The intro line stays attached to the table header via the
            table's own `minPresenceAhead` - section heading + capacity
            notice + the first few rows always land on the same page. */}
        <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];
  // Filter the default set to the requested subset; preserve the
  // ordering from the override array so reps can reorder columns
  // via the saved-template UI in phase C.
  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: ClientReportData['rows'][number]): string {
  switch (key) {
    case 'fullName':
      return row.fullName;
    case 'primaryEmail':
      return row.primaryEmail ?? '';
    case 'primaryPhone':
      return row.primaryPhone ?? '';
    case 'source':
      return row.source ?? '';
    case 'nationality':
      return row.nationality ?? '';
    case 'createdAt':
      return new Date(row.createdAt).toLocaleDateString('en-GB');
    default:
      return '';
  }
}
