import React, {useMemo} from 'react';
import {Column} from 'react-table';
import {LoadingState} from './types';
import {EmptyStateCell} from './style';

const useLoadingState = (
  showLoadingState: boolean,
  loading: boolean,
  pageSize: number,
  columns: Column[],
  LoadingCellComponent = (props: any) => <EmptyStateCell {...props} />,
): LoadingState => {
  const loadingColumns: Column[] | undefined = useMemo(() => (showLoadingState && loading ? columns
    .map(({maxWidth, width, Header}: Column, key: number) => {
      const column: Column = {
        Cell: LoadingCellComponent,
        accessor: `empty_${key}`,
        filterable: false,
        sortable: false,
      };
      if (maxWidth) {
        column.maxWidth = maxWidth;
      }
      if (width) {
        column.maxWidth = width;
      }
      if (Header) {
        column.Header = Header;
      }

      return column;
    }) : []), [LoadingCellComponent, columns, loading, showLoadingState]);

  const loadingData = useMemo(() => {
    if (showLoadingState && loading && columns && columns.length > 0) {
      const dataObject: any = {};
      const dataArray: any[] = [];

      for (let i = 0; i < columns.length; i += 1) {
        dataObject[`empty_${i}`] = '';
      }
      for (let i = 0; i < pageSize; i += 1) {
        dataArray.push(dataObject);
      }

      return dataArray;
    }

    return [];
  }, [columns, loading, pageSize, showLoadingState]);

  return {
    loadingColumns,
    loadingData,
  };
};

export default useLoadingState;
