import type { ScaleOrdinal } from 'd3-scale'
import { scaleBand } from 'd3-scale'
import type { FC } from 'react'
import { useMemo } from 'react'
import type { PlotDataElement } from '../types'
import Bar from './Bar'
import type { YScale } from './types'

interface BarGroupProps {
  data: PlotDataElement[]
  colorScale: ScaleOrdinal<string, string, never>
  range: number[]
  onClick: (element: PlotDataElement) => void
  getOpacity: (element: PlotDataElement) => number
  yScale: YScale
  height: number
}

const BarGroup: FC<BarGroupProps> = ({
  data,
  colorScale,
  range,
  onClick,
  getOpacity,
  yScale,
  height,
}) => {
  const groups = data.map(dataElement => dataElement.name)
  const xScale = useMemo(
    () => scaleBand().domain(groups).range(range).padding(0.05),
    [groups, range]
  )

  return data.map(d => (
    <Bar
      key={d.name}
      dataElement={d}
      colorScale={colorScale}
      onClick={() => onClick(d)}
      opacity={getOpacity(d)}
      xScale={xScale}
      yScale={yScale}
      height={height}
    />
  ))
}

export default BarGroup
