import type { FC } from 'react'
import { useContext } from 'react'
import ExerciseContext from '../../ExerciseContext'
import useFormatTimestamp from '../../useFormatTimestamp'
import { MIN_TO_MS } from '../../utilities'
import {
  getAutoInjectName,
  getAutoInjectTime,
  getAutoInjectType,
  type AutoInject,
} from './utils'

interface TooltipTimestampProps {
  autoInject: AutoInject
}

const TooltipTimestamp: FC<TooltipTimestampProps> = ({ autoInject }) => {
  const { exercise } = useContext(ExerciseContext)
  const formatTimestamp = useFormatTimestamp()

  return (
    <>
      <strong>Timestamp: </strong>
      <span>
        {formatTimestamp(
          new Date(
            (exercise.exerciseStart
              ? new Date(exercise.exerciseStart).getTime()
              : 0) +
              getAutoInjectTime(autoInject) * MIN_TO_MS
          ).toISOString()
        )}
      </span>
      <br />
    </>
  )
}

interface AutoInjectTooltipProps {
  autoInjects: AutoInject[]
}

const AutoInjectTooltip: FC<AutoInjectTooltipProps> = ({ autoInjects }) => (
  <>
    {autoInjects.length > 1 && (
      <>
        <TooltipTimestamp autoInject={autoInjects[0]} />
        <br />
      </>
    )}
    {autoInjects.slice(0, 2).map((inject, i) => (
      <div key={inject.id}>
        {autoInjects.length > 1 && (
          <>
            <em>{`${i + 1}:`}</em>
            <br />
          </>
        )}
        <strong>Name: </strong>
        <span>{getAutoInjectName(inject)}</span>
        <br />
        <strong>Type: </strong>
        <span>{getAutoInjectType(inject)}</span>
        <br />
        {autoInjects.length < 2 && <TooltipTimestamp autoInject={inject} />}
      </div>
    ))}
    {autoInjects.length > 2 && (
      <>
        <br />
        <em>{`+ ${autoInjects.length - 2} more`}</em>
      </>
    )}
  </>
)

export default AutoInjectTooltip
