import cx from 'classnames';
import { number, oneOfType, string, oneOf, bool } from 'prop-types';
import { Stack } from '../Layout/index';
import Icon from '../Icon/index';
import * as React from 'react';
import style from './Healthscore.module.scss';

const SmallHealthscore = ({ isProcessing, score, ...rest }) => (
  <div {...rest}>{isProcessing ? <Icon name="clock" color="Mid Neutral 2" /> : score}</div>
);

const LargeHealthscore = ({ isProcessing, text, score, ...rest }) => (
  <div {...rest}>
    <Stack gap="none" textAlign="center">
      {!isProcessing && <div>{score}</div>}
      <div className={style.text}>{text}</div>
    </Stack>
  </div>
);

const Healthscore = ({ size, score, className, isActive, isProcessing, ...props }) => {
  function getHealthText(score, isProcessing) {
    if (isProcessing) return 'Updating...';
    if (score === 'NA') return '';
    if (score <= 50) return 'Poor';
    if (score > 50 && score <= 80) return 'Average';
    return 'Healthy';
  }

  function getHealthColorClassName(score) {
    if (score === 'NA') return 'NA';
    if (score <= 50) return 'unhealthy';
    if (score > 50 && score <= 80) return 'average';
    return 'healthy';
  }

  const healthScoreClass = cx(
    style.healthScore,
    style[getHealthColorClassName(score)],
    style[size],
    isActive && style.active,
    className,
  );
  if (size === 'small')
    return (
      <SmallHealthscore
        score={score}
        isProcessing={isProcessing}
        className={healthScoreClass}
        {...props}
      />
    );
  return (
    <LargeHealthscore
      isProcessing={isProcessing}
      text={getHealthText(score, isProcessing)}
      score={score}
      className={healthScoreClass}
      {...props}
    />
  );
};

export default Healthscore;

Healthscore.propTypes = {
  isProcessing: bool,
  score: oneOfType([string, number]),
  size: oneOf(['small', 'large']),
};

Healthscore.defaultProps = {
  isProcessing: false,
  score: 'NA',
  size: 'small',
};
