import React, { useMemo, useRef } from 'react';
import { Popover } from 'antd';
import styles from './ThresholdBar.less';

const ThresholdBar = props => {
  const { current, thresholds = [] } = props;
  const boxRef = useRef();

  const { min, max } = useMemo(() => {
    let myThresholds = [...thresholds];
    if (thresholds.length == 1) {
      if (thresholds[0] > current) {
        return { min: '', max: thresholds[0] };
      } else {
        return { min: thresholds[0], max: '' };
      }
    }
    myThresholds.sort((a, b) => a - b);
    let index = myThresholds.findIndex(item => item > current);
    return { min: myThresholds[index - 1], max: myThresholds[index] };
  }, [current, thresholds]);

  const getLeft = () => {
    if (thresholds.length == 1) {
      if (thresholds[0] > current) {
        return 0;
      } else {
        return '100%';
      }
    } else {
      let number = (current - min) / (max - min);
      return number * 100 + '%';
    }
  };

  return (
    <div className={styles.bar}>
      <div className={styles.box} ref={boxRef}>
        <div className={`${styles.scale} ${styles.min}`}>{min}</div>
        <div className={`${styles.scale} ${styles.max}`}>{max}</div>
        <div className={`${styles.scale} ${styles.top}`} style={{ left: getLeft() }}>
          {parseFloat(current).toFixed(2)}
        </div>
        <div className={styles.current} style={{ left: getLeft() }}>
          <div className={styles.currentBar}></div>
        </div>
      </div>
    </div>
  );
};

export default ThresholdBar;
