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

import { CN_ERROR_INLINE } from '../component';

const Wrap = styled.div`
  display: flex;
  align-items: baseline;
  padding: ${props => props.isInForm ? `${REM_UNIT_XSM} ${REM_UNIT_LG} ${REM_UNIT_SM}` : `${REM_UNIT_MD} 0`};
  ${props => props.isInModal && `padding: 0 ${REM_UNIT_LG}`};
  text-align: left;
  font-family: ${FONT_BOLD};
  color: ${props => props.isInfoVariant ? VERY_LIGHT_TANGELO : SUNSET_ORANGE};
`;

const ErrorMessage = styled.p`
  font-size: ${REM_FONT_SIZE_NORMAL};
`;

class ErrorInline extends React.Component {
  shouldComponentUpdate(prevProps) {
    if (prevProps.isInfoVariant !== this.props.isInfoVariant) return true;
    if (prevProps.asyncStatus !== this.props.asyncStatus) return true;
    if (prevProps.asyncStatusList !== this.props.asyncStatusList) return true;
    return false;
  }

  render() {
    const { isInModal, isInForm, infoMessage, asyncStatus, asyncStatusList, className } = this.props;
    const { isSuccessful, isError, errorMessage } = determineAsyncStatus({ asyncStatus, asyncStatusList });
    const isInfoVariant = this.props.isInfoVariant && isSuccessful;

    return (
      (isError || isInfoVariant) ?
        <Wrap
          isInfoVariant={isInfoVariant}
          isInModal={isInModal}
          isInForm={isInForm}
          className={`${className} ${CN_ERROR_INLINE}`}
        >
          <ErrorMessage>
            {errorMessage || infoMessage}
          </ErrorMessage>
        </Wrap> : null
    );
  }
}

ErrorInline.propTypes = {
  isInfoVariant: bool,
  isInModal: bool,
  isInForm: bool,
  infoMessage: string,
  asyncStatus: shape(PROP_ASYNC_STATUS),
  asyncStatusList: arrayOf(shape(PROP_ASYNC_STATUS)),
  className: string,
};

ErrorInline.defaultProps = {
  isInfoVariant: false,
  isInModal: false,
  isInForm: false,
  infoMessage: undefined,
  asyncStatus: SHAPE_ASYNC_STATUS_INITIAL,
  asyncStatusList: [],
  className: undefined,
};

export default ErrorInline;
