import useFormatTimestamp from '@/analyst/useFormatTimestamp'
import { HIGHLIGHTED_COLOR, ellipsized } from '@/analyst/utilities'
import { textFromRenderedContent } from '@/utils'
import { Card, Classes, Icon } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import type { Email } from '@inject/graphql/fragments/Email.generated'
import type { EmailThread } from '@inject/graphql/fragments/EmailThread.generated'
import { useSetIsUnreadEmailThread } from '@inject/graphql/mutations/clientonly/SetIsUnreadEmailThread.generated'
import Timestamp from '@inject/shared/components/Timestamp'
import { useMemo, type FC } from 'react'

const timestamp = css`
  white-space: nowrap;

  @media (max-width: 80rem) {
    display: none;
  }
`

interface ThreadLogCardProps {
  emailThread: EmailThread
  lastEmail: Email
  teamId: string
  isSelected?: boolean
  onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
  inAnalyst?: boolean
}

const ThreadLogCard: FC<ThreadLogCardProps> = ({
  emailThread,
  lastEmail,
  teamId,
  isSelected,
  onClick,
  inAnalyst,
}) => {
  const formatTimestamp = useFormatTimestamp()

  const [setIsRead] = useSetIsUnreadEmailThread({
    variables: {
      threadId: emailThread.id,
      isUnread: false,
      teamId,
    },
  })

  const isUnread = useMemo(
    () =>
      emailThread.readReceipt.some(
        readReceipt => readReceipt.teamId === teamId && readReceipt.isUnread
      ),
    [emailThread.readReceipt, teamId]
  )

  return (
    <Card
      interactive
      onClick={event => {
        setIsRead()
        onClick(event)
      }}
      style={{
        background: isSelected
          ? 'rgba(45, 114, 210, 0.2)'
          : isUnread
            ? HIGHLIGHTED_COLOR
            : undefined,
        display: 'flex',
        justifyContent: 'space-between',
        gap: '0.25rem',
      }}
    >
      <div className={cx(Classes.SECTION_HEADER_LEFT, ellipsized)}>
        <div className={ellipsized}>
          <div className={ellipsized}>
            <span
              style={{
                fontWeight: 'normal',
                fontStyle: 'italic',
              }}
            >
              {lastEmail.sender.team?.id === teamId ? 'to: ' : 'from: '}
            </span>
            {lastEmail.sender.team?.id === teamId
              ? emailThread.participants
                  .filter(participant => participant.team?.id !== teamId)
                  .map(participant => participant.address)
                  .join(', ')
              : lastEmail.sender.address}
          </div>
          <h6
            className={cx(
              Classes.HEADING,
              Classes.SECTION_HEADER_TITLE,
              ellipsized
            )}
          >
            {lastEmail.content.fileInfo && (
              <Icon
                icon='paperclip'
                className={Classes.TEXT_MUTED}
                style={{ paddingRight: '0.25em' }}
              />
            )}
            {emailThread.subject}
          </h6>
          {textFromRenderedContent(lastEmail.content.rendered)}
        </div>
      </div>
      <div className={Classes.SECTION_HEADER_RIGHT}>
        <span className={timestamp}>
          {inAnalyst ? (
            formatTimestamp(lastEmail.timestamp)
          ) : (
            <Timestamp
              minimal
              datetime={new Date(lastEmail.timestamp)}
              isRead={!isUnread}
            />
          )}
        </span>
        <Icon icon='chevron-right' className={Classes.TEXT_MUTED} />
      </div>
    </Card>
  )
}

export default ThreadLogCard
