import React, { useMemo } from 'react'
import withDefaults from '../utils/with-defaults'
import Progress from '../progress'
import useTheme from '../use-theme'
import { ProgressColors } from '../progress/progress'

export interface MetricCardBarGaugeProps {
  value: number
  min?: number
  max?: number
  average?: number
  className?: string
  color?: string
  colors?: ProgressColors
  loading: boolean
}

const defaultProps = {
  min: 0,
  max: 100,
  className: '',
  loading: false
}

type NativeAttrs = Omit<React.HTMLAttributes<any>, keyof MetricCardBarGaugeProps>
export type MetricCardBarGaugeComponentProps = MetricCardBarGaugeProps &
  typeof defaultProps &
  NativeAttrs

const MetricCardBarGauge: React.FC<MetricCardBarGaugeComponentProps> = ({
  value,
  min,
  max,
  average,
  className,
  color,
  colors,
  loading
}) => {
  const theme = useTheme()
  const hasAverage = average !== undefined && average !== null
  const { percentage, percentageAverage } = useMemo(
    () => ({
      percentage: ((value - min) / max) * 100,
      percentageAverage: average ? ((average - min) / max) * 100 : 0
    }),
    [value, min, max, average]
  )
  const margin = hasAverage ? '-10px 0' : '0'
  const chartColor = color || 'var(--token-color-system-success-10)'

  const colorProps = useMemo(() => {
    if (colors) {
      return {
        colors
      }
    }
    return {
      color: loading ? 'transparent' : chartColor
    }
  }, [colors, chartColor])
  return (
    <div className={`line-chart ${className}`}>
      {hasAverage && <div className="average-tick" title={`Average: ${average}`} />}
      <Progress value={percentage || 0} {...colorProps} />
      {hasAverage && <div className="average-tick" title={`Average: ${average}`} />}
      <style jsx>{`
        .line-chart {
          margin: ${margin};
          padding-bottom: ${theme.layout.gapQuarter};
        }
        .line-chart .average-tick {
          opacity: ${loading ? 0 : 1};
          height: 10px;
          width: ${percentageAverage}%;
        }
        .line-chart .average-tick:after {
          content: '';
          float: right;
          background: ${chartColor};
          width: 2px;
          height: 6px;
          margin: 2px 0;
          border-radius: 1px;
        }
      `}</style>
    </div>
  )
}

const MemoCardContent = React.memo(MetricCardBarGauge)

export default withDefaults(MemoCardContent, defaultProps)
