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

import type { KeyValueItem } from '../../model/types';
import { styles } from '../styles';

export function KeyValueGrid(props: { items: KeyValueItem[] }): React.ReactElement | null {
  const items = (props.items || []).filter((i) => i.label && i.value);
  if (!items.length) return null;

  // 4-column layout: (label, value, label, value)
  const rows: Array<[KeyValueItem, KeyValueItem | null]> = [];
  for (let i = 0; i < items.length; i += 2) {
    rows.push([items[i], items[i + 1] || null]);
  }

  return (
    <View style={styles.kvGrid}>
      {rows.map(([left, right], rowIndex) => {
        const isLast = rowIndex === rows.length - 1;
        const leftValue = left.unit ? `${left.value} ${left.unit}` : left.value;
        const rightValue = right ? (right.unit ? `${right.value} ${right.unit}` : right.value) : '';

        return (
          <View
            key={`${left.label}-${rowIndex}`}
            style={[
              styles.kvRow,
              rowIndex % 2 === 0 ? styles.kvRowAlt : null,
              isLast ? styles.kvRowLast : null,
            ]}
            wrap={false}
          >
            <View style={[styles.kvCell, { width: '23%' }]}>
              <Text style={styles.kvLabelText}>{left.label}</Text>
            </View>
            <View style={[styles.kvCell, styles.kvMidDivider, { width: '27%' }]}>
              <Text style={styles.kvValueText}>{leftValue}</Text>
            </View>
            <View style={[styles.kvCell, { width: '23%' }]}>
              <Text style={styles.kvLabelText}>{right?.label || ''}</Text>
            </View>
            <View style={[styles.kvCell, { width: '27%' }]}>
              <Text style={styles.kvValueText}>{rightValue}</Text>
            </View>
          </View>
        );
      })}
    </View>
  );
}
