import useFormatTimestamp from '@/analyst/useFormatTimestamp'
import { textFromRenderedContent } from '@/utils'
import { Button, Card, Classes, Colors, Icon } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import type { Email, EmailThread } from '@inject/graphql/fragment-types'
import type { VariablesOf } from '@inject/graphql/graphql'
import { SetEmailThreadArchive } 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 { ellipsized } from '@inject/shared/css/textOverflow'
import { useMemo, type FC } from 'react'

const card = css`
  display: flex;
  justify-content: space-between;
  position: relative;
  gap: 0.25rem;
`

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

  .bp5-dark & {
    background-color: ${Colors.ORANGE5}26 !important;
  }

  &:hover {
    background-color: ${Colors.GRAY3}26 !important;
  }
`

const selected = css`
  background-color: ${Colors.BLUE2}33 !important;

  &:hover {
    background-color: ${Colors.BLUE4}26 !important;
  }
`

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 client = useClient()

  const isUnread = useMemo(
    () => emailThread.emails.some(email => !email.readReceipt),
    [emailThread.emails]
  )
  const order =
    Math.trunc(
      new Date(emailThread.lastEmail?.timestamp || '0').valueOf() / 1000
    ) % 2147483647

  return (
    <Card
      className={cx({
        [card]: true,
        [unread]: !inAnalyst && isUnread,
        [selected]: isSelected,
      })}
      style={{ order }}
      interactive
      onClick={onClick}
    >
      {!inAnalyst && (
        <Button
          className={css`
            position: absolute;
            top: 0.25rem;
            right: 0.25rem;
          `}
          minimal
          title='Archive/Unarchive thread'
          onClick={e => {
            e.stopPropagation()
            client
              .mutation<unknown, VariablesOf<typeof SetEmailThreadArchive>>(
                SetEmailThreadArchive,
                {
                  emailThreadId: emailThread.id,
                  state: !emailThread.archived,
                }
              )
              .then()
          }}
          icon={emailThread.archived ? 'unarchive' : 'archive'}
        />
      )}
      <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 ? (
            <StyledTag
              isRead={!isUnread}
              content={formatTimestamp(emailThread.lastEmail?.timestamp || '0')}
            />
          ) : (
            <Timestamp
              isRead={!isUnread}
              datetime={new Date(emailThread.lastEmail?.timestamp || '0')}
              minimal
            />
          )}
        </span>
        <Icon icon='chevron-right' className={Classes.TEXT_MUTED} />
      </div>
    </Card>
  )
}

export default ThreadLogCard
