import React from 'react';
import { bool, string, arrayOf, shape } from 'prop-types';
import styled from 'styled-components';
import { REM_UNIT_XSM, REM_FONT_SIZE___SM, VERY_LIGHT_TANGELO, SUNSET_ORANGE } from '@vincent_za/styles';
import { PROP_ASYNC_STATUS, SHAPE_ASYNC_STATUS_INITIAL, determineAsyncStatus } from '@vincent_za/utils';

export const CN_ERROR_FIELD = 'error-field';

const Wrap = styled.div`
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: ${REM_UNIT_XSM};
  font-size: ${REM_FONT_SIZE___SM};
  color: ${props => props.isInfoVariant ? VERY_LIGHT_TANGELO : SUNSET_ORANGE};
`;

class FieldError extends React.PureComponent {
  render() {
    const { isInfoVariant, infoMessage, fieldStatus, asyncStatus, asyncStatusList, className } = this.props;
    const { isError, errorMessage } = fieldStatus || determineAsyncStatus({ asyncStatus, asyncStatusList });

    return (
      !isError ? null :
      <Wrap isErrorVariant={!isInfoVariant} isInfoVariant={isInfoVariant} className={`${className} ${CN_ERROR_FIELD}`}>
        {errorMessage || infoMessage}
      </Wrap>
    );
  }
}

FieldError.propTypes = {
  isInfoVariant: bool,
  infoMessage: string,
  fieldStatus: shape({ isError: bool, errorMessage: string }),
  asyncStatus: shape(PROP_ASYNC_STATUS),
  asyncStatusList: arrayOf(shape(PROP_ASYNC_STATUS)),
  className: string,
};

FieldError.defaultProps = {
  isInfoVariant: false,
  infoMessage: undefined,
  fieldStatus: {},
  asyncStatus: SHAPE_ASYNC_STATUS_INITIAL,
  asyncStatusList: [],
  className: undefined,
};

export default FieldError;
