import React from 'react';
import { Cell, Column, Id, ReactGrid, Row } from '@silevis/reactgrid';
import { useMemo, useState } from 'react';
import { ITableData } from './api/datasource';
import '@silevis/reactgrid/styles.css';

interface IProps {
  data: ITableData;
}

const getText = (value: any): string => {
  if (value === null || value === undefined) {
    return '';
  } else if (typeof value === 'object') {
    return JSON.stringify(value);
  } else {
    return value.toString();
  }
};

const DataTable = ({ data }: IProps): JSX.Element => {
  const [cols, setCols] = useState<Column[]>(() =>
    Object.keys(data).map(columnId => {
      return { columnId, width: 100, resizable: true };
    })
  );

  const rows = useMemo((): Row<Cell>[] => {
    const colNames = Object.keys(data);
    const header = {
      rowId: 'header',
      cells: colNames.map(text => {
        return {
          text,
          type: 'header'
        };
      })
    };
    const dataRows = Object.keys(data[colNames[0]]).map(rowId => {
      return {
        rowId,
        cells: colNames.map(c => {
          return {
            type: 'text',
            text: getText(data[c][rowId]),
            nonEditable: true
          };
        })
      };
    });
    return [header, ...dataRows];
  }, [data]);

  const handleColumnResize = (ci: Id, width: number) => {
    setCols(prevColumns => {
      const columnIndex = prevColumns.findIndex(el => el.columnId === ci);
      const resizedColumn = prevColumns[columnIndex];
      const updatedColumn = { ...resizedColumn, width };
      prevColumns[columnIndex] = updatedColumn;
      return [...prevColumns];
    });
  };

  return (
    <div style={{ width: '100%', height: '100%', overflow: 'scroll' }}>
      <ReactGrid
        enableRangeSelection
        stickyTopRows={1}
        rows={rows}
        columns={cols}
        onColumnResized={handleColumnResize}
      />
    </div>
  );
};

export default DataTable;
