/**
 * TEAM: frontend_infra
 *
 * @flow strict
 */

import * as React from "react";

import {css, StyleSheet} from "aphrodite";

import {whitespaceSizeConstants} from "../styles/whitespace";
import colors from "../colors";
import Text from "../Text";

export type ColumnDefinition<T> = {|
  +id: string,
  +header: string,
  +getText: T => string,
|};

/**
 * @short Simple wrapper around native html table
 * @category Data Display
 *
 * Use `<SimpleTable />` to display read-only tabular data.
 * If you need to paginate data, use filters, or define
 * custom actions use the Table component instead.
 *
 *
 */
export default function SimpleTable<T>({
  data,
  columnDefinitions,
  getUniqueRowId,
  useFullWidth = false,
}: {|
  /** An array of rows where each row is an object containing a key and an array containing string values */
  +data: $ReadOnlyArray<T>,
  /** An array of strings for each column header definition in the table */
  +columnDefinitions: $ReadOnlyArray<ColumnDefinition<T>>,
  /** A function to uniquely identify each row, this ID is what is returned in the row selections set */
  +getUniqueRowId: T => string,
  /** Table size expands to the full width of the container */
  +useFullWidth?: boolean,
|}): React.Element<"table"> {
  data.forEach(row => {
    columnDefinitions.forEach(columnDef => {
      columnDef.getText(row);
    });
  });
  return (
    <table className={css(useFullWidth && styles.fullWidth)}>
      <thead>
        <tr>
          {columnDefinitions.map(columnDef => (
            <th className={css(styles.header)} key={columnDef.id}>
              <Text color="grey40">{columnDef.header}</Text>
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.map(currentRow => (
          <tr key={getUniqueRowId(currentRow)}>
            {columnDefinitions.map(columnDef => (
              <td className={css(styles.tableItems)} key={columnDef.id}>
                <Text>{columnDef.getText(currentRow)}</Text>
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

const styles = StyleSheet.create({
  header: {
    paddingLeft: whitespaceSizeConstants.s,
    paddingRight: whitespaceSizeConstants.s,
    paddingBottom: whitespaceSizeConstants.xs,
    borderBottom: `1px solid ${colors.grey30}`,
  },
  tableItems: {
    paddingTop: whitespaceSizeConstants.xs,
    paddingBottom: whitespaceSizeConstants.xs,
    paddingLeft: whitespaceSizeConstants.s,
    paddingRight: whitespaceSizeConstants.s,
  },
  fullWidth: {
    width: "100%",
  },
});
