import FileViewRedirectButton from '@/components/FileViewRedirectButton'
import type { EmailDetails } from '@inject/graphql/fragments/EmailDetails.generated'
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
}

const EmailDetail: FC<EmailDetailProps> = ({ emailDetails }) => {
  const { exercise } = useContext(ExerciseContext)
  const formatTimestamp = useFormatTimestamp()
  const teamId = emailDetails.thread.participants
    .filter(participant => participant.team)
    .at(0)?.team?.id

  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}
              aria-label='renderedContent'
              dangerouslySetInnerHTML={{
                __html: emailDetails.content.rendered,
              }}
            />
          </tr>
          {emailDetails.content.fileInfo && teamId && (
            <tr>
              <th className={th}>Attached file</th>
              <td className={td}>
                <FileViewRedirectButton
                  fileInfo={emailDetails.content.fileInfo}
                  teamId={teamId}
                  exerciseId={exercise.id}
                  inInstructor
                />
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  )
}

export default EmailDetail
