import React from "react";
import { GetItemsResponse, Item as PluckyItem } from "plucky_client/plucky";
import styles from "./item_table.module.css";
import { ItemRow } from "./item_row";
import classNames from "classnames/bind";
import { QueryRange } from "utils";

export type ItemTableProps = {
  data: GetItemsResponse;
  queryRange: QueryRange;
  serviceURLSlug: string;
};

export function ItemTable(props: ItemTableProps) {
  // Only show up to 500 rows.
  // This prevents us from running into an issue with Chrome where it limits the number of rows
  // in a grid to 1000. https://github.com/rachelandrew/gridbugs/issues/28
  const items = props.data.items.slice(0, 500);

  const hasOperation = items.some(
    (item: PluckyItem) => !!item.lastOccurrence.operation
  );

  const operationHeader = hasOperation ? (
    <div className={styles.header}>Operation</div>
  ) : null;

  const rows = items.map((item: PluckyItem) => (
    <ItemRow
      item={item}
      key={item.fingerprint}
      queryRange={props.queryRange}
      serviceURLSlug={props.serviceURLSlug}
      showOperation={hasOperation}
    />
  ));

  return (
    <div
      className={styles.table}
      style={{
        gridTemplateColumns: `max-content 1fr repeat(6, max-content)`,
      }}
    >
      <div className={classNames(styles.header, styles.itemHeader)}>Item</div>
      <div className={styles.header}>Trend</div>
      <div className={classNames(styles.header, styles.totalCell)}>Total</div>
      <div className={styles.header}>Last</div>
      {operationHeader}
      <div className={styles.header}>Level</div>
      <div className={styles.header} />
      <div className={styles.rowLine} />
      {rows}
    </div>
  );
}
