import { Tooltip } from '@blueprintjs/core'
import type { DefinitionInject } from '@inject/graphql/fragment-types'
import type { FC } from 'react'
import { useContext, useRef } from 'react'
import ExerciseContext from '../ExerciseContext'
import type { XScale } from '../Plots/ScatterPlot/types'
import { MIN_TO_MS, plotDataElement } from '../utilities'
import CategoryTooltip from './CategoryTooltip'
import FilterContext from './FilterContext'

const WIDTH = 2

interface CategoryLineProps {
  injectGroup: DefinitionInject[]
  onClick: () => void
  xScale: XScale
  height: number
}

const CategoryLine: FC<CategoryLineProps> = ({
  injectGroup,
  onClick,
  xScale,
  height,
}) => {
  const ref = useRef<SVGRectElement>(null)

  const { exercise } = useContext(ExerciseContext)

  const { displayCategories, displayInjectCategories, displayEmailCategories } =
    useContext(FilterContext)

  return (
    <Tooltip
      targetTagName='g'
      content={
        <CategoryTooltip
          injectGroup={injectGroup.filter(
            injectGroup =>
              (displayInjectCategories && injectGroup.type !== 'EMAIL') ||
              (displayEmailCategories && injectGroup.type === 'EMAIL')
          )}
        />
      }
      position='right'
    >
      <rect
        ref={ref}
        className={plotDataElement}
        x={
          xScale(
            (exercise.exerciseStart
              ? new Date(exercise.exerciseStart).getTime()
              : 0) +
              (injectGroup[0].time + injectGroup[0].delay) * MIN_TO_MS
          ) -
          WIDTH / 2
        }
        y={0}
        width={WIDTH}
        height={height}
        fill='#808080'
        onClick={onClick}
        style={{
          display:
            displayCategories &&
            ((displayInjectCategories &&
              injectGroup.some(inject => inject.type !== 'EMAIL')) ||
              (displayEmailCategories &&
                injectGroup.some(inject => inject.type === 'EMAIL')))
              ? 'initial'
              : 'none',
        }}
      />
    </Tooltip>
  )
}

export default CategoryLine
