import React from 'react';

interface StatementMetric<Row> {
  key: string;
  label: string;
  render: (period: Row) => React.ReactNode;
}

interface StatementTablePanelProps<Row extends { label: string }> {
  periods: Row[];
  metrics: StatementMetric<Row>[];
}

const numericFormatter = new Intl.NumberFormat('en-US', {
  maximumFractionDigits: 2,
});

const isMissingNumber = (value: number | null | undefined): value is null | undefined =>
  value === null || value === undefined || Number.isNaN(value);

export const formatMoney = (value?: number | null) => {
  if (isMissingNumber(value)) return '—';
  if (Math.abs(value) >= 1e12) return `$${(value / 1e12).toFixed(2)}T`;
  if (Math.abs(value) >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
  if (Math.abs(value) >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;
  return `$${numericFormatter.format(value)}`;
};

export const formatNumber = (value?: number | null) =>
  isMissingNumber(value) ? '—' : numericFormatter.format(value);

export const formatPercent = (value?: number | null) =>
  isMissingNumber(value) ? '—' : `${value >= 0 ? '+' : ''}${value.toFixed(1)}%`;

export function StatementTablePanel<Row extends { label: string }>({
  periods,
  metrics,
}: StatementTablePanelProps<Row>) {
  return (
    <div className="overflow-auto rounded border border-term-border">
      <table className="min-w-full border-collapse font-mono text-sm">
        <thead className="bg-term-highlight text-term-text-muted">
          <tr>
            <th className="sticky left-0 border-r border-b border-term-border bg-term-highlight px-3 py-2 text-left text-[10px] uppercase tracking-[0.18em]">
              Item
            </th>
            {periods.map((period) => (
              <th
                key={period.label}
                className="border-b border-term-border px-3 py-2 text-right text-[10px] uppercase tracking-[0.18em]"
              >
                {period.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {metrics.map((metric) => (
            <tr key={metric.key} className="border-b border-term-border-subtle last:border-b-0">
              <th className="sticky left-0 border-r border-term-border-subtle bg-term-surface px-3 py-2 text-left font-medium text-term-text">
                {metric.label}
              </th>
              {periods.map((period) => (
                <td key={`${metric.key}-${period.label}`} className="px-3 py-2 text-right text-term-text">
                  {metric.render(period)}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
