import React from 'react'
import { findLast } from 'ramda'
import cx from 'classnames'
import colors from './mt-colors'

const { red, green, yellow } = colors

function getValueColor (actualWidth, thresholds) {
  return findLast(({ start }) => start < actualWidth, thresholds)
}

function getSafeRatio (ratio) {
  const isInvalid = Number.isNaN(ratio) || typeof ratio !== 'number'
  return isInvalid ? 0 : ratio
}

const ProgressBar = (props) => {
  const { ratio, thresholds, className } = props

  const safeRatio = getSafeRatio(ratio)
  const valueWidth = safeRatio <= 1 ? safeRatio * 100 : 100

  const valueStyle = {
    width: `${valueWidth}%`,
    backgroundColor: getValueColor(safeRatio, thresholds).color,
  }

  return (
    <div className={ cx('progress-bar', className) } style={ valueStyle } />
  )
}

const MTSingleProgressBar = (props) => {
  const {
    ratio,
    height,
    width,
    thresholds,
    className,
    ...otherProps
  } = props

  const barStyle = {
    height,
    width,
  }

  return (
    <div
      { ...otherProps }
      className={ cx('single-progress-bar', className) }
      style={ barStyle }
    >
      <ProgressBar
        ratio={ ratio }
        thresholds={ thresholds }
      />
    </div>
  )
}

MTSingleProgressBar.defaultProps = {
  height: '10px',
  width: '100px',
  thresholds: [ {
    start: -Infinity,
    color: red,
  }, {
    start: 0.80,
    color: yellow,
  }, {
    start: 0.90,
    color: green,
  } ],
}

export default MTSingleProgressBar
