import React from 'react';

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

interface StatementTableMinimalProps<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 StatementTableMinimal<Row extends { label: string }>({
  periods,
  metrics,
}: StatementTableMinimalProps<Row>) {
  return (
    <div className="overflow-x-auto">
      <table className="min-w-full border-collapse font-mono text-sm">
        <thead className="text-[#888888]">
          <tr className="border-b border-[#1a1a1a]">
            <th className="sticky left-0 border-r border-[#1a1a1a] bg-[#0a0a0a] 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-[#1a1a1a] 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-[#1a1a1a] last:border-b-0">
              <th className="sticky left-0 border-r border-[#1a1a1a] bg-[#0a0a0a] px-3 py-2 text-left font-medium text-[#cfcfcf]">
                {metric.label}
              </th>
              {periods.map((period) => (
                <td key={`${metric.key}-${period.label}`} className="px-3 py-2 text-right text-[#e0e0e0]">
                  {metric.render(period)}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
