import FileViewRedirectButton from '@/components/FileViewRedirectButton'
import { Button, Card } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { EmailTemplate } from '@inject/graphql/fragments/EmailTemplate.generated'
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>
        <tr>
          <th className={th}>Context</th>
          <td className={td}>{template.context || '-'}</td>
        </tr>
        <tr>
          <th className={th}>Sender</th>
          <td className={td}>{template.sender || '-'}</td>
        </tr>
        <tr>
          <th className={th}>Activate milestones</th>
          <td className={td}>{template.control.activateMilestone || '-'}</td>
        </tr>
        <tr>
          <th className={th}>Deactivate milestones</th>
          <td className={td}>{template.control.deactivateMilestone || '-'}</td>
        </tr>
        <tr>
          <th className={th}>Content</th>
          <td
            className={td}
            aria-label='renderedContent'
            dangerouslySetInnerHTML={{
              __html: template.content.rendered || '-',
            }}
          />
        </tr>
        <tr>
          <th className={th}>Attached file</th>
          <td className={td}>
            {template.content.fileInfo ? (
              <FileViewRedirectButton
                fileInfo={template.content.fileInfo}
                teamId={teamId}
                exerciseId={exerciseId}
                inInstructor
              />
            ) : (
              '-'
            )}
          </td>
        </tr>
      </tbody>
    </table>

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

export default TemplateCard
