import React from 'react'
import cn from 'classnames'

const MTPercentageGauge = React.forwardRef((props, ref) => {
  const {
    percentage,
    width,
    maskColor,
    progressColor,
    fullColor,
    showPercentage,
    children,
    className,
    ...otherProps
  } = props

  const r = width / 2
  const strokeWidth = width / 10
  const meterDimension = (r * 2) + (strokeWidth * 2)
  const calcPercentage = percentage <= 100 ? percentage : 100

  const gaugeStyle = {
    width: meterDimension,
    height: meterDimension / 2,
  }

  const percetageFontSize = width / 4
  const percentageStyle = {
    top: (meterDimension / 2) - (percetageFontSize * 1.2),
    fontSize: percetageFontSize,
  }

  function polarToCartesian (cx, cy, radius, angle) {
    const radians = ((angle - 90) * Math.PI) / 180.0
    return [
      Math.round((cx + (radius * Math.cos(radians))) * 100) / 100,
      Math.round((cy + (radius * Math.sin(radians))) * 100) / 100,
    ]
  }

  function getSvgCircleArcPath (x, y, radius, startAngle, endAngle) {
    const startXY = polarToCartesian(x, y, radius, endAngle)
    const endXY = polarToCartesian(x, y, radius, startAngle)
    return `M ${startXY[0]} ${startXY[1]} A ${radius} ${radius} 0 0 0 ${endXY[0]} ${endXY[1]}`
  }

  return (
    <div
      { ...otherProps }
      className={ cn('mt-percentage-gauge', className) }
      style={ gaugeStyle }
      ref={ ref }
    >
      <div className="mt-percentage-gauge__inner">
        <svg viewBox="0 0 1000 500">
          <path
            d="M 950 500 A 450 450 0 0 0 50 500"
            style={ {
              strokeWidth: 75,
              stroke: maskColor,
              fill: 'none',
            } }
          />
          <path
            d={ getSvgCircleArcPath(500, 500, 450, -90, ((calcPercentage / 100) * 180) - 90) }
            style={ {
              strokeWidth: 75,
              stroke: percentage < 100 ? progressColor : fullColor,
              fill: 'none',
            } }
          />
        </svg>
        { showPercentage && (
          <div className="mt-percentage-gauge__percentage" style={ percentageStyle }>
            { children ?? `${percentage} %` }
          </div>
        ) }
      </div>
    </div>
  )
})

MTPercentageGauge.defaultProps = {
  width: 50,
  percentage: 0,
  progressColor: '#15ca7d',
  fullColor: '#f6634b',
  maskColor: '#e7e8e9',
  showPercentage: true,
}

export default MTPercentageGauge
