import React from 'react';
import ReactTable, {TableProps} from 'react-table';

import {CommonStyles} from './style';

import useLoadingState from './useLoadingState';

const Table = ({
  data,
  columns = [],
  defaultPageSize = 20,
  loading = false,
  defaultSorted = [],
  pageText = 'page',
  ofText = 'of',
  previousText = 'Previous page',
  nextText = 'Next page',
  loadingText = 'Loading...',
  noDataText = 'Woops, no data.',
  getTrProps,
  manual = false,
  filterable = true,
  showPagination,
  showPageSizeOptions = false,
  showPageJump = false,
  style = {},
  ExpanderComponent,
  SubComponent,
  resizable = false,
  showLoadingState = false,
  LoadingCellComponent,
  defaultFilterMethod = (filter, row) => String(row[filter.id])
    .toLowerCase()
    .includes(filter.value.toLowerCase()),
  ...rest
}: Partial<TableProps> & { showLoadingState: boolean, LoadingCellComponent?: (props: any) => React.ReactElement}) => {
  const {loadingColumns, loadingData} = useLoadingState(
    showLoadingState, loading, defaultPageSize, columns, LoadingCellComponent,
  );
  const showLoading = showLoadingState && loading;
  return (
    <>
      <ReactTable
        data={showLoading ? loadingData : data}
        columns={showLoading ? loadingColumns : columns}
        defaultPageSize={defaultPageSize}
        filterable={filterable}
        defaultSorted={defaultSorted}
        showPagination={!showLoading && showPagination}
        showPageSizeOptions={showPageSizeOptions}
        showPageJump={showPageJump}
        loading={!showLoadingState && loading}
        resizable={resizable}
        minRows={0}
        pageText={pageText}
        ofText={ofText}
        previousText={previousText}
        nextText={nextText}
        loadingText={loadingText}
        noDataText={noDataText}
        defaultFilterMethod={defaultFilterMethod}
        getTrProps={getTrProps}
        manual={manual}
        style={style}
        ExpanderComponent={ExpanderComponent}
        SubComponent={SubComponent}
        {...rest}
      />
      <CommonStyles />
    </>
  );
};

Table.defaultProps = {
  LoadingCellComponent: undefined,
};

export {Table};
