import useFormatTimestamp from '@/analyst/useFormatTimestamp'
import FileViewRedirectButton from '@/components/FileViewRedirectButton'
import RenderedContent from '@/components/RenderedContent'
import {
  Button,
  Classes,
  Colors,
  Icon,
  Section,
  SectionCard,
} from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import type { VariablesOf } from '@inject/graphql/graphql'
import { WriteReadReceiptEmail } from '@inject/graphql/mutations.client'
import { useClient } from '@inject/graphql/urql/client'
import StyledTag from '@inject/shared/components/StyledTag'
import Timestamp from '@inject/shared/components/StyledTag/Timestamp'
import { breakWord } from '@inject/shared/css/textOverflow'
import type { FC } from 'react'
import { useEffect, useLayoutEffect, useState } from 'react'
import { OPEN_COMPOSE_EVENT_TYPE } from '../EmailFormOverlay'
import type { ExtendedEmail } from '../typing'
import { getForwardContent } from './getForwardContent'

const section = css`
  overflow: unset;

  .${Classes.SECTION_HEADER} {
    flex-wrap: wrap;
    gap: unset;
  }
`

const unread = css`
  background-color: ${Colors.GRAY1}26 !important;
`

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

interface EmailCardProps {
  exerciseId: string
  teamId: string
  email: ExtendedEmail
  inAnalyst?: boolean
  allowForwarding?: boolean
  forwardButtonTitle?: string
  inInstructor: boolean
}

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

  const client = useClient()
  // this ensures the message is rendered as 'not read' the first time it's rendered
  const [initialReadReceipt, setInitialReadReceipt] = useState(false)

  useLayoutEffect(() => {
    if (!email.readReceipt) {
      setInitialReadReceipt(true)
    }
  }, [email.readReceipt])

  useEffect(() => {
    // you can't use URQL calls in layout effects
    if (initialReadReceipt) {
      client
        .mutation<
          unknown,
          VariablesOf<typeof WriteReadReceiptEmail>
        >(WriteReadReceiptEmail, { emailId: email.id })
        .then()
    }
  }, [client, email.id, initialReadReceipt])

  return (
    <Section
      className={cx({ [section]: true, [unread]: initialReadReceipt === null })}
      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 ? (
            <StyledTag
              isRead={!initialReadReceipt}
              content={formatTimestamp(email.timestamp)}
            />
          ) : (
            <Timestamp
              isRead={!initialReadReceipt}
              datetime={new Date(email.timestamp)}
              minimal
            />
          )}
          {(allowForwarding || forwardButtonTitle) && (
            <Button
              minimal
              rightIcon='nest'
              title={forwardButtonTitle}
              disabled={!allowForwarding}
              onClick={() =>
                window.dispatchEvent(
                  new CustomEvent(OPEN_COMPOSE_EVENT_TYPE, {
                    detail: {
                      content: getForwardContent(email),
                      fileInfo: email.content.fileInfo,
                      subject: `Fwd: ${email.subject}`,
                    },
                  })
                )
              }
            >
              Forward
            </Button>
          )}
        </div>
      }
    >
      <SectionCard padded>
        <RenderedContent
          className={breakWord}
          teamId={teamId}
          renderedContent={email.content.rendered}
          inInstructor={inInstructor}
        />
        {email.content.fileInfo && (
          <FileViewRedirectButton
            teamId={teamId}
            fileInfo={email.content.fileInfo}
            exerciseId={exerciseId}
          />
        )}
      </SectionCard>
    </Section>
  )
}

export default EmailCard
