import { findLast, isEmpty } from 'ramda'
import React, { useEffect } from 'react'
import ReactTooltip from 'react-tooltip'
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 MTProgressBar = (props) => {
  const {
    ratio,
    height,
    backgroundColor,
    thresholds,
    targetColor,
    targetHint,
    valueHint,
    valuePaddingPercentage,
    barWidthRatioAdded,
    className,
    ...otherProps
  } = props

  useEffect(() => {
    ReactTooltip.rebuild()
  }, [])

  const barStyle = {
    height,
    backgroundColor,
  }
  const safeRatio = getSafeRatio(ratio)
  const fullWidthRatio = safeRatio <= 1 ? 1 + barWidthRatioAdded : safeRatio + barWidthRatioAdded
  const valueWidth = (safeRatio / fullWidthRatio) * 100
  const valueStyle = {
    width: `${valueWidth}%`,
    top: `${valuePaddingPercentage}%`,
    height: `${100 - (2 * valuePaddingPercentage)}%`,
    backgroundColor: getValueColor(safeRatio, thresholds).color,
  }
  const targetStyle = {
    display: safeRatio <= 1 && barWidthRatioAdded === 0 ? 'none' : 'block',
    left: `${100 / fullWidthRatio}%`,
    backgroundColor: targetColor,
  }
  const valHint = isEmpty(valueHint) ? `${safeRatio * 100}%` : valueHint

  return (
    <div
      { ...otherProps }
      className={ cx('mt-progress-bar', className) }
      style={ barStyle }
    >
      <div className="mt-progress-bar__target" data-tip={ targetHint } style={ targetStyle } />
      <div className="mt-progress-bar__value" data-tip={ valHint } style={ valueStyle } />
    </div>
  )
}

MTProgressBar.defaultProps = {
  height: '10px',
  targetColor: '#000000',
  targetHint: '100%',
  valuePaddingPercentage: 25,
  barWidthRatioAdded: 0.2,
  thresholds: [ {
    start: -Infinity,
    color: red,
  }, {
    start: 0.80,
    color: yellow,
  }, {
    start: 0.90,
    color: green,
  } ],
  valueHint: '',
}

export default MTProgressBar
