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

import { PDF_TOKENS } from './tokens';

const styles = StyleSheet.create({
  grid: {
    flexDirection: 'column',
    gap: PDF_TOKENS.spacing.rowGap,
  },
  twoCol: {
    flexDirection: 'row',
    gap: PDF_TOKENS.spacing.sectionGap,
  },
  cell: {
    flexBasis: '50%',
    flexDirection: 'column',
    gap: 2,
  },
  fullRow: {
    flexDirection: 'row',
    gap: 8,
    alignItems: 'flex-start',
  },
  label: {
    fontFamily: PDF_TOKENS.fonts.sansBold,
    fontSize: PDF_TOKENS.sizes.small,
    color: PDF_TOKENS.colors.textMuted,
    textTransform: 'uppercase',
    letterSpacing: 0.4,
  },
  value: {
    fontFamily: PDF_TOKENS.fonts.sans,
    fontSize: PDF_TOKENS.sizes.body,
    color: PDF_TOKENS.colors.text,
  },
});

export type KvRow = { label: string; value: string | number | null | undefined };

export interface KeyValueGridProps {
  rows: KvRow[];
  /** Render as two-column layout (default) or stacked. */
  layout?: 'two-col' | 'stacked';
}

function fmt(v: string | number | null | undefined): string {
  if (v === null || v === undefined || v === '') return '-';
  return typeof v === 'number' ? String(v) : v;
}

export function KeyValueGrid({ rows, layout = 'two-col' }: KeyValueGridProps) {
  if (layout === 'stacked') {
    return (
      <View style={styles.grid}>
        {rows.map((r, i) => (
          <View key={i} style={styles.cell}>
            <Text style={styles.label}>{r.label}</Text>
            <Text style={styles.value}>{fmt(r.value)}</Text>
          </View>
        ))}
      </View>
    );
  }
  const pairs: KvRow[][] = [];
  for (let i = 0; i < rows.length; i += 2) {
    pairs.push([rows[i]!, rows[i + 1] ?? { label: '', value: '' }]);
  }
  return (
    <View style={styles.grid}>
      {pairs.map((pair, i) => (
        <View key={i} style={styles.twoCol}>
          <View style={styles.cell}>
            {pair[0]?.label ? (
              <>
                <Text style={styles.label}>{pair[0].label}</Text>
                <Text style={styles.value}>{fmt(pair[0].value)}</Text>
              </>
            ) : null}
          </View>
          <View style={styles.cell}>
            {pair[1]?.label ? (
              <>
                <Text style={styles.label}>{pair[1].label}</Text>
                <Text style={styles.value}>{fmt(pair[1].value)}</Text>
              </>
            ) : null}
          </View>
        </View>
      ))}
    </View>
  );
}
