import { css } from '@emotion/css'
import type { FC } from 'react'
import { Fragment, useContext } from 'react'
import ExerciseContext from '../../ExerciseContext'
import useFormatTimestamp from '../../useFormatTimestamp'
import { MIN_TO_MS } from '../../utilities'
import { td, th } from '../detailStyles'
import {
  getAutoInjectName,
  getAutoInjectTime,
  getAutoInjectType,
  type AutoInject,
} from './utils'

const wrapper = css`
  display: flex;
  flex-direction: column;
  gap: 1rem;
`

interface DetailTimestampProps {
  autoInject: AutoInject
}

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

  return (
    <tr>
      <th className={th}>Timestamp</th>
      <td className={td}>
        {formatTimestamp(
          new Date(
            (exercise.exerciseStart
              ? new Date(exercise.exerciseStart).getTime()
              : 0) +
              getAutoInjectTime(autoInject) * MIN_TO_MS
          ).toISOString()
        )}
      </td>
    </tr>
  )
}

interface AutoInjectDetailProps {
  autoInjects: AutoInject[]
}

const AutoInjectDetail: FC<AutoInjectDetailProps> = ({ autoInjects }) => (
  <div className={wrapper}>
    <table>
      <tbody>
        {autoInjects.length > 1 && (
          <DetailTimestamp autoInject={autoInjects[0]} />
        )}
        {autoInjects.map((inject, i) => (
          <Fragment key={inject.id}>
            {autoInjects.length > 1 && (
              <tr>
                <td>
                  <em>{`${i + 1}:`}</em>
                </td>
              </tr>
            )}
            <tr>
              <th className={th}>Name</th>
              <td className={td}>{getAutoInjectName(inject)}</td>
            </tr>
            <tr>
              <th className={th}>Type</th>
              <td className={td}>{getAutoInjectType(inject)}</td>
            </tr>
            {autoInjects.length < 2 && <DetailTimestamp autoInject={inject} />}
          </Fragment>
        ))}
      </tbody>
    </table>
  </div>
)

export default AutoInjectDetail
