import FileViewRedirectButton from '@/components/FileViewRedirectButton'
import RenderedContent from '@/components/RenderedContent'
import type { EmailDetails } from '@inject/graphql/fragment-types'
import type { FC } from 'react'
import { useContext } from 'react'
import ExerciseContext from '../ExerciseContext'
import useFormatTimestamp from '../useFormatTimestamp'
import { td, th } from './detailStyles'

interface EmailDetailProps {
  emailDetails: EmailDetails
  teamId: string
}

const EmailDetail: FC<EmailDetailProps> = ({ emailDetails, teamId }) => {
  const { exercise } = useContext(ExerciseContext)
  const formatTimestamp = useFormatTimestamp()

  return (
    <div>
      <table>
        <tbody>
          <tr>
            <th className={th}>Thread subject</th>
            <td className={td}>{emailDetails.thread.subject}</td>
          </tr>
          <tr>
            <th className={th}>Thread participants</th>
            <td className={td}>
              {emailDetails.thread.participants
                .map(participant => participant.address)
                .join(', ')}
            </td>
          </tr>
          <tr>
            <th className={th}>Timestamp</th>
            <td className={td}>{formatTimestamp(emailDetails.timestamp)}</td>
          </tr>
          <tr>
            <th className={th}>Sender</th>
            <td className={td}>{emailDetails.sender.address}</td>
          </tr>
          <tr>
            <th className={th}>Content</th>
            <td className={td}>
              <RenderedContent
                teamId={teamId}
                inInstructor
                renderedContent={emailDetails.content.rendered}
              />
            </td>
          </tr>
          {emailDetails.content.fileInfo && (
            <tr>
              <th className={th}>Attached file</th>
              <td className={td}>
                <FileViewRedirectButton
                  fileInfo={emailDetails.content.fileInfo}
                  teamId={teamId}
                  exerciseId={exercise.id}
                />
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  )
}

export default EmailDetail
