import React from 'react';
import { number, bool, string, arrayOf, shape } from 'prop-types';
import styled from 'styled-components';
import { JET } from '@vincent_za/styles';
import { PROP_ASYNC_STATUS, SHAPE_ASYNC_STATUS_INITIAL, determineAsyncStatus } from '@vincent_za/utils';
import { loaderSvg } from '@vincent_za/assets';
import Svg from '../../Svg/component';

const Wrap = styled.div`
  display: flex;
  ${props => !props.isStatic && `
    z-index: 2;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  `}
`;

const Overlay = styled.div`
  display: ${props => props.hasOverlay ? 'block' : 'none'};
  width: 100%;
  height: 100%;
  background-color: ${JET};
`;

const LoaderStyled = styled(Svg)`
  ${props => !props.isStatic && `
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  `}

  path {
    &:nth-child(1) {
      fill: rgba(0, 0, 0, 0.5);
    };
    &:nth-child(2) {
      fill: rgba(255,255,255,0.5);
    };
  }
`;

class SpinnerLoader extends React.PureComponent {
  render() {
    const { isAlwaysVisible, asyncStatus, asyncStatusList, hasOverlay, width, size, isStatic, className } = this.props;
    const { isInitial, isBusy } = determineAsyncStatus({ asyncStatus, asyncStatusList });

    return (
      !isInitial && null,
      (isInitial || isAlwaysVisible) && isBusy &&
      <Wrap isStatic={isStatic} className={className}>
        <Overlay hasOverlay={hasOverlay} />
        <LoaderStyled width={width} size={size} isStatic={isStatic} svg={loaderSvg} />
      </Wrap>
    );
  }
}

SpinnerLoader.propTypes = {
  isAlwaysVisible: bool,
  asyncStatus: shape(PROP_ASYNC_STATUS),
  asyncStatusList: arrayOf(shape(PROP_ASYNC_STATUS)),
  hasOverlay: bool,
  size: number,
  width: number,
  isStatic: bool,
  className: string,
};

SpinnerLoader.defaultProps = {
  isAlwaysVisible: false,
  asyncStatus: SHAPE_ASYNC_STATUS_INITIAL,
  asyncStatusList: [],
  hasOverlay: false,
  size: 4,
  width: 4,
  isStatic: false,
  className: '',
};

export default SpinnerLoader;
