import FileViewRedirectButton from '@/components/FileViewRedirectButton'
import RenderedContent from '@/components/RenderedContent'
import { Button, Card } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { EmailTemplate } from '@inject/graphql/fragment-types'
import type { FC, MouseEvent, MouseEventHandler } from 'react'

const th = css`
  text-align: left;
  vertical-align: text-top;
  white-space: nowrap;
  padding: 0.25rem 0.5rem;
`

const td = css`
  white-space: pre-wrap;
  vertical-align: text-top;
  padding: 0.25rem 0.5rem;
  width: 100%;
`

const card = css`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin: 1rem;
`

interface TemplateCardProps {
  template: EmailTemplate
  teamId: string
  exerciseId: string
  onClick: ((event: MouseEvent<HTMLElement, globalThis.MouseEvent>) => void) &
    MouseEventHandler<HTMLButtonElement>
}

const TemplateCard: FC<TemplateCardProps> = ({
  template,
  teamId,
  exerciseId,
  onClick,
}) => (
  <Card key={template.id} className={card}>
    <table>
      <tbody>
        {template.context && (
          <tr>
            <th className={th}>Context</th>
            <td className={td}>{template.context}</td>
          </tr>
        )}
        {template.subject && (
          <tr>
            <th className={th}>Subject</th>
            <td className={td}>{template.subject}</td>
          </tr>
        )}
        {template.sender && (
          <tr>
            <th className={th}>Sender</th>
            <td className={td}>{template.sender}</td>
          </tr>
        )}
        {template.control.activateMilestone && (
          <tr>
            <th className={th}>Activate milestones</th>
            <td className={td}>{template.control.activateMilestone}</td>
          </tr>
        )}
        {template.control.deactivateMilestone && (
          <tr>
            <th className={th}>Deactivate milestones</th>
            <td className={td}>{template.control.deactivateMilestone}</td>
          </tr>
        )}
        {template.content.rendered && (
          <tr>
            <th className={th}>Content</th>
            <td className={td}>
              <RenderedContent
                teamId={teamId}
                inInstructor
                renderedContent={template.content.rendered}
              />
            </td>
          </tr>
        )}
        {template.content.fileInfo && (
          <tr>
            <th className={th}>Attached file</th>
            <td className={td}>
              <FileViewRedirectButton
                fileInfo={template.content.fileInfo}
                teamId={teamId}
                exerciseId={exerciseId}
              />
            </td>
          </tr>
        )}
      </tbody>
    </table>

    <Button
      style={{ marginTop: '1rem', alignSelf: 'end' }}
      type='button'
      onClick={onClick}
    >
      Select
    </Button>
  </Card>
)

export default TemplateCard
