import { Tooltip } from '@blueprintjs/core'
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 FilterContext from '../FilterContext'
import AutoInjectTooltip from './AutoInjectTooltip'
import {
  getAutoInjectFilter,
  getAutoInjectTime,
  type AutoInject,
} from './utils'

const WIDTH = 2

interface AutoInjectLineProps {
  autoInjects: AutoInject[]
  onClick: () => void
  xScale: XScale
  height: number
}

const AutoInjectLine: FC<AutoInjectLineProps> = ({
  autoInjects,
  onClick,
  xScale,
  height,
}) => {
  const ref = useRef<SVGRectElement>(null)

  const { exercise } = useContext(ExerciseContext)

  const {
    displayAllAutoInjects,
    displayAutoInjects,
    displayAutoEmails,
    displayAutoQuestionnaires,
  } = useContext(FilterContext)

  return (
    <Tooltip
      targetTagName='g'
      content={
        <AutoInjectTooltip
          autoInjects={autoInjects.filter(
            getAutoInjectFilter(
              displayAutoInjects,
              displayAutoEmails,
              displayAutoQuestionnaires
            )
          )}
        />
      }
      position='right'
    >
      <rect
        ref={ref}
        className={plotDataElement}
        x={
          xScale(
            (exercise.exerciseStart
              ? new Date(exercise.exerciseStart).getTime()
              : 0) +
              getAutoInjectTime(autoInjects[0]) * MIN_TO_MS
          ) -
          WIDTH / 2
        }
        y={0}
        width={WIDTH}
        height={height}
        fill='#808080'
        onClick={onClick}
        style={{
          display:
            displayAllAutoInjects &&
            autoInjects.some(
              getAutoInjectFilter(
                displayAutoInjects,
                displayAutoEmails,
                displayAutoQuestionnaires
              )
            )
              ? 'initial'
              : 'none',
        }}
      />
    </Tooltip>
  )
}

export default AutoInjectLine
