import React, { Fragment } from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types';
import {
  LoadingContainer,
  LoadingRow,
  LoadingItemContainer,
  LoadingStateContainer,
} from './styledComponents';
import { LoadingProps } from '../../interface';
import ItemDisplay from '../ItemDisplay/ItemDisplay';
import ActionButton from '../ActionButton';

const EMPTY_LOADING_ROW = 8;

const LoadingState = (props: LoadingProps): JSX.Element => {
  const { headers, hasNestedData } = props;
  return (
    <LoadingStateContainer>
      {_.times(EMPTY_LOADING_ROW, (index) => (
        <LoadingContainer key={`loading-${index}`}>
          <LoadingRow>
            {headers.map((header, rowIndex) => {
              const key = `row-${index}-${rowIndex}`;
              const isAction = header.propertyKey === 'action';
              const { isHidden } = header;

              return (
                <Fragment key={key}>
                  {!isAction && (
                    <LoadingItemContainer
                      large={header.large}
                      minWidth={header.minWidth}
                      nbColumn={headers.length}
                      narrow={header.narrow}
                    >
                      <ItemDisplay
                        value=""
                        large={header.large}
                        nbColumn={headers.length}
                        isLoading
                      />
                    </LoadingItemContainer>
                  )}

                  {isAction && !hasNestedData && (
                    <div style={{ flex: 4 }}>
                      <ActionButton isLoading visibility={!isHidden} />
                    </div>
                  )}
                </Fragment>
              );
            })}
          </LoadingRow>
        </LoadingContainer>
      ))}
    </LoadingStateContainer>
  );
};

LoadingState.propTypes = {
  headers: PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string.isRequired,
      propertyKey: PropTypes.string.isRequired,
      isNumber: PropTypes.bool,
      unit: PropTypes.string,
      tooltipDisplay: PropTypes.string,
      large: PropTypes.bool,
      narrow: PropTypes.bool,
      minWidth: PropTypes.number,
      bold: PropTypes.bool,
      textTransform: PropTypes.string,
      textDecorationChild: PropTypes.string,
      hrefPrefix: PropTypes.string,
      hrefSuffix: PropTypes.string,
      render: PropTypes.func,
      graphConfiguration: PropTypes.shape({
        title: PropTypes.string,
        subtitle: PropTypes.string,
      }),
    })
  ).isRequired,
};

LoadingState.defaultProps = {};

export default LoadingState;
