import { brushX } from 'd3-brush'
import { select } from 'd3-selection'
import type { Dispatch, FC, SetStateAction } from 'react'
import { useEffect, useRef } from 'react'
import type { XScale } from './types'

interface BrushProps {
  setStartTime: Dispatch<SetStateAction<number>>
  setEndTime: Dispatch<SetStateAction<number>>
  width: number
  height: number
  xScale: XScale
}

const Brush: FC<BrushProps> = ({
  setStartTime,
  setEndTime,
  width,
  height,
  xScale,
}) => {
  const ref = useRef<SVGGElement>(null)

  const brush = brushX()
    .extent([
      [0, 0],
      [width, Math.max(height - 1, 0)],
    ])
    .on('end', event => {
      if (event.selection == null) {
        return
      }

      if (ref.current) {
        select(ref.current).call(brush.move, null)
      }

      setStartTime(xScale.invert(event.selection[0]).getTime())
      setEndTime(xScale.invert(event.selection[1]).getTime())
    })

  useEffect(() => {
    if (ref.current) {
      select(ref.current).call(brush)
    }
  }, [brush, xScale])

  return <g ref={ref} />
}

export default Brush
