import useFormatTimestamp from '@/analyst/useFormatTimestamp'
import { HIGHLIGHTED_COLOR } from '@/analyst/utilities'
import FileViewRedirectButton from '@/components/FileViewRedirectButton'
import { Button, Classes, Icon, Section, SectionCard } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Email } from '@inject/graphql/fragments/Email.generated'
import { useWriteReadReceiptEmail } from '@inject/graphql/mutations/clientonly/WriteReadReceiptEmail.generated'
import Timestamp from '@inject/shared/components/Timestamp'
import type { FC } from 'react'
import { useEffect, useMemo } from 'react'
import { OPEN_COMPOSE_EVENT_TYPE } from '../EmailFormOverlay'
import getForwardContent from './getForwardContent'

const section = css`
  .${Classes.SECTION_HEADER} {
    flex-wrap: wrap;
    gap: unset;
  }
`

const rightElement = css`
  display: flex;
  justify-content: space-between;
  gap: 0.5rem;
  align-items: center;
`

interface EmailCardProps {
  exerciseId: string
  teamId: string
  email: Email
  inAnalyst?: boolean
  inInstructor?: boolean
  allowForwarding?: boolean
  forwardButtonTitle?: string
  subject: string
  to: string
}

const EmailCard: FC<EmailCardProps> = ({
  exerciseId,
  teamId,
  email,
  inAnalyst,
  inInstructor,
  allowForwarding,
  forwardButtonTitle,
  subject,
  to,
}) => {
  const formatTimestamp = useFormatTimestamp()

  // this ensures the message is rendered as 'not read' the first time it's rendered
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const initialReadReceipt = useMemo(() => email.readReceipt, [])
  const [mutate] = useWriteReadReceiptEmail({
    variables: { emailId: email.id },
  })
  useEffect(() => {
    if (!email.readReceipt) {
      mutate()
    }
  }, [email.readReceipt, mutate])

  return (
    <Section
      className={section}
      style={{
        background: initialReadReceipt ? undefined : HIGHLIGHTED_COLOR,
        overflow: 'unset',
      }}
      icon={
        email.sender.team?.id === teamId ? (
          <Icon
            className={Classes.TEXT_MUTED}
            icon='send-message'
            title='sent by the selected team'
          />
        ) : (
          <Icon
            className={Classes.TEXT_MUTED}
            icon='envelope'
            title='received by the selected team'
          />
        )
      }
      title={email.sender.address}
      rightElement={
        <div className={rightElement}>
          {inAnalyst ? (
            formatTimestamp(email.timestamp)
          ) : (
            <Timestamp
              minimal
              datetime={new Date(email.timestamp)}
              isRead={initialReadReceipt !== null}
            />
          )}
          <Button
            minimal
            icon='nest'
            disabled={!allowForwarding}
            title={forwardButtonTitle}
            onClick={() =>
              window.dispatchEvent(
                new CustomEvent(OPEN_COMPOSE_EVENT_TYPE, {
                  detail: {
                    content: getForwardContent(email, to),
                    fileInfo: email.content.fileInfo,
                    subject: `Fwd: ${subject}`,
                  },
                })
              )
            }
          >
            Forward
          </Button>
        </div>
      }
    >
      <SectionCard>
        <div
          style={{
            margin: '0em 0em 0em 0em',
            wordWrap: 'break-word',
            whiteSpace: 'pre-wrap',
          }}
          dangerouslySetInnerHTML={{ __html: email.content.rendered }}
        />
        {email.content.fileInfo && (
          <FileViewRedirectButton
            teamId={teamId}
            fileInfo={email.content.fileInfo}
            exerciseId={exerciseId}
            inInstructor={inInstructor}
          />
        )}
      </SectionCard>
    </Section>
  )
}

export default EmailCard
