import { Tooltip } from '@blueprintjs/core'
import type { ScaleOrdinal } from 'd3-scale'
import type { FC } from 'react'
import { useRef } from 'react'
import { plotDataElement } from '../../utilities'
import type { PlotDataElement } from '../types'
import type { XScale, YScale } from './types'

interface BarProps {
  dataElement: PlotDataElement
  colorScale: ScaleOrdinal<string, string, never>
  onClick: () => void
  opacity: number
  xScale: XScale
  yScale: YScale
  height: number
}

const Bar: FC<BarProps> = ({
  dataElement,
  colorScale,
  onClick,
  opacity,
  xScale,
  yScale,
  height,
}) => {
  const ref = useRef<SVGRectElement>(null)

  return (
    <Tooltip
      targetTagName='g'
      content={<span>{`${dataElement.name}: ${dataElement.value}`}</span>}
      position='top'
    >
      <rect
        ref={ref}
        className={plotDataElement}
        x={xScale(dataElement.name)}
        y={yScale(dataElement.value)}
        width={xScale.bandwidth()}
        height={height - yScale(dataElement.value)}
        fill={colorScale(dataElement.name)}
        opacity={opacity}
        onClick={onClick}
      />
    </Tooltip>
  )
}

export default Bar
