import { useMemo } from 'react';
import { Table, TableColumn } from 'components/table/Table';

type AnalyticsTableValue = string;

type AnalyticsColumn = TableColumn<AnalyticsTableValue> & {
  range?: [number, number];
};

const interpolate = (x: number, a: number, b: number, c: number, d: number) =>
  ((x - a) * (d - c)) / (b - a) + c;

const colorScale = (x: number, a: number, b: number) =>
  interpolate(x, a, b, 130, 360);

export const AnalyticsTable = ({
  data,
  options,
}: {
  data: string;
  options: string;
  // data: ObjectFromEntries[];
  // options: AnalyticsColumn[];
}) => {
  const rows: Record<string, AnalyticsTableValue>[] = useMemo(
    () => JSON.parse(data),
    [data]
  );
  const columns: AnalyticsColumn[] = useMemo(
    () => JSON.parse(options),
    [options]
  );
  const cols = columns.map((col) => {
    if (col.range) {
      const [min, max] = col.range;
      col.computedStyle = (value) => {
        const hue = colorScale(Number(value), max, min);
        return {
          color: `hsl(${hue},55%,45%)`,
          // backgroundColor: `hsl(${hue},100%,80%)`,
        };
      };
    }

    return col;
  });

  return (
    <Table
      className="fz14"
      style={{ margin: '0 -16px' }}
      rows={rows}
      columns={cols}
    />
  );
};
