import React from 'react';
import cn from 'classnames';
import { useTable, useExpanded } from 'react-table';

type FlightTableProps = {
  data: {
    date: string;
    type: string;
    aircraft: string;
    route: string;
    depArr: string;
    pilot: string;
    coPilot: string;
  }[];
  columns: any;
  renderRowSubComponent: any;
};

export const FlightTable: React.FC<FlightTableProps> = ({
  columns,
  data,
  renderRowSubComponent,
}: FlightTableProps) => {
  const classes = cn('bfo-flight-table');
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    visibleColumns,
  } = useTable(
    {
      columns,
      data,
    },
    useExpanded, // We can useExpanded to track the expanded state
    // for sub components too!
  );

  return (
    <div className={classes}>
      <table {...getTableProps()}>
        {headerGroups.length > 0 && (
          <thead>
            {headerGroups.map(headerGroup => (
              <tr key={headerGroup.id} {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map(column => (
                  <th key="add key here" {...column.getHeaderProps()}>
                    {column.render('Header')}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
        )}
        <tbody {...getTableBodyProps()}>
          {rows.map(row => {
            prepareRow(row);
            return (
              // Use a React.Fragment here so the table markup is still valid
              <React.Fragment key={row.id}>
                <tr>
                  {row.cells.map(cell => {
                    return (
                      <td key={cell.column.id} {...cell.getCellProps()}>
                        {cell.render('Cell')}
                      </td>
                    );
                  })}
                </tr>
                {/*
                    If the row is in an expanded state, render a row with a
                    column that fills the entire length of the table.
                  */}
                {row.isExpanded ? (
                  <tr>
                    <td colSpan={visibleColumns.length}>
                      {/*
                          Inside it, call our renderRowSubComponent function. In reality,
                          you could pass whatever you want as props to
                          a component like this, including the entire
                          table instance. But for this example, we'll just
                          pass the row
                        */}
                      {renderRowSubComponent({ row })}
                    </td>
                  </tr>
                ) : null}
              </React.Fragment>
            );
          })}
        </tbody>
      </table>
      <br />
    </div>
  );
};
