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(() => {
    const needle = emailThread.readReceipt.find(
      readReceipt => readReceipt.teamId === teamId
    )
    return needle?.isUnread
  }, [emailThread.readReceipt, teamId])

  return (
    <Card
      className={cx({
        [card]: true,
        [unread]: !inAnalyst && isUnread,
        [selected]: isSelected,
      })}
      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(lastEmail.timestamp)}
            />
          ) : (
            <Timestamp
              isRead={!isUnread}
              datetime={new Date(lastEmail.timestamp)}
              minimal
            />
          )}
        </span>
        <Icon icon='chevron-right' className={Classes.TEXT_MUTED} />
      </div>
    </Card>
  )
}

export default ThreadLogCard
