import Category from "../../types/category";
import './Histogram.scss';

function Histogram({ categories }: Props) {
  const maxAbsBalanceToBudgetRatio = Math.max(
    ...categories.map((c) => Math.abs(c.balanceToBudgetRatio))
  );

  return (
    <table>
      <thead>
        <tr>
          <th>Category</th>
          <th>Balance-to-Budget Ratio</th>
          <th>Balance</th>
        </tr>
      </thead>

      <tbody>
        {
          categories
            .sort((c1, c2) => c1.balanceToBudgetRatio - c2.balanceToBudgetRatio)
            .map((category) => Row({ category, maxAbsBalanceToBudgetRatio }))
        }
      </tbody>
    </table>
  );
}

function Row({ category, maxAbsBalanceToBudgetRatio }: RowProps) {
  const normalisedRatio = category.balanceToBudgetRatio / maxAbsBalanceToBudgetRatio;
  const variant = getRowVariant(new Number(normalisedRatio).valueOf());

  return (
    <tr>
      <td class="name">{category.name}</td>
      <td
        class={`ratio ratio--${variant}`}
        style={`--normal-abs-ratio: ${Math.abs(normalisedRatio)};`}
      >
        <span class="ratio__text">
          {category.balanceToBudgetRatio.toFixed(2)}
        </span>
        <span class="ratio__bar"></span>
      </td>
      <td class="balance">{category.currentBalance.toString()}</td>
    </tr>
  );
}

function getRowVariant(balanceToBudgetRatio: number) {
  if (balanceToBudgetRatio < 0) {
    return 'arrears';
  }
  if (balanceToBudgetRatio >= 1) {
    return 'spend';
  }
  return 'save';
}

type Props = {
  categories: Category[],
};

type RowProps = {
  category: Category,
  maxAbsBalanceToBudgetRatio: number,
};

export default Histogram;
