import { textFromRenderedContent } from '@/utils'
import type {
  ActionLog,
  CustomInjectDetails,
  EmailDetails,
  InjectDetails,
  QuestionnaireDetails,
  ToolDetails,
} from '@inject/graphql/fragment-types'
import type { FC } from 'react'
import useFormatTimestamp from '../useFormatTimestamp'

const getContent = (actionLog: ActionLog) => {
  let details
  switch (actionLog.type) {
    case 'INJECT':
      details = actionLog.details as InjectDetails
      return (
        <>
          {details.inject.organization && (
            <>
              <strong>Organization: </strong>
              <span>{details.inject.organization}</span>
              <br />
            </>
          )}
          <strong>Content: </strong>
          <span>{textFromRenderedContent(details.content.rendered)}</span>
        </>
      )
    case 'CUSTOM_INJECT':
      details = actionLog.details as CustomInjectDetails
      return (
        <>
          <strong>Content: </strong>
          <span>{textFromRenderedContent(details.content.rendered)}</span>
        </>
      )
    case 'TOOL':
      details = actionLog.details as ToolDetails
      return (
        <>
          <strong>Tool: </strong>
          <span>{details.tool.name}</span>
          <br />
          {details.tool.requiresInput && (
            <>
              <strong>Argument: </strong>
              <span>{details.argument}</span>
              <br />
            </>
          )}
          <strong>Response: </strong>
          <span>{textFromRenderedContent(details.content.rendered)}</span>
        </>
      )
    case 'FORM':
      details = actionLog.details as QuestionnaireDetails
      return (
        <>
          <strong>Title: </strong>
          <span>{details.title}</span>
        </>
      )
    case 'EMAIL':
      details = actionLog.details as EmailDetails
      return (
        <>
          <strong>Sender: </strong>
          <span>{details.sender.address}</span>
          <br />
          <strong>Subject: </strong>
          <span>{details.thread.subject}</span>
          <br />
          <strong>Content: </strong>
          <span>{textFromRenderedContent(details.content.rendered)}</span>
        </>
      )
    default:
      throw new Error(`unknown actionLog type: ${actionLog.type}`)
  }
}

interface ActionTooltipProps {
  actionLog: ActionLog
}

const ActionTooltip: FC<ActionTooltipProps> = ({ actionLog }) => {
  const formatTimestamp = useFormatTimestamp()

  return (
    <>
      <strong>Type: </strong>
      <span>{actionLog.type}</span>
      <br />
      {getContent(actionLog)}
      <br />
      <strong>Timestamp: </strong>
      <span>{formatTimestamp(actionLog.timestamp)}</span>
    </>
  )
}

export default ActionTooltip
