import { ellipsized } from '@/analyst/utilities'
import { Card, Classes, Icon } from '@blueprintjs/core'
import { cx } from '@emotion/css'
import type { EmailThread } from '@inject/graphql/fragments/EmailThread.generated'
import type { EmailDraft } from '@inject/graphql/fragments/clientonly/EmailDraft.generated'
import { useGetEmailThread } from '@inject/graphql/queries/GetEmailThread.generated'
import notEmpty from '@inject/shared/utils/notEmpty'
import { useMemo, type FC } from 'react'

interface DraftLogCardProps {
  teamId: string
  emailDraft: EmailDraft
  isSelected: boolean
  onClick: (emailThread?: EmailThread | null) => void
}

const DraftLogCard: FC<DraftLogCardProps> = ({
  teamId,
  emailDraft,
  isSelected,
  onClick,
}) => {
  const { data } = useGetEmailThread({
    variables: {
      threadId: emailDraft.emailThreadId || '',
    },
    skip: !emailDraft.emailThreadId,
  })

  const subject = useMemo(() => {
    if (data?.emailThread?.subject) {
      return `Reply to: ${data.emailThread.subject}`
    }
    if (emailDraft.subject) {
      return `New email: ${emailDraft.subject}`
    }
    return `New email`
  }, [data?.emailThread?.subject, emailDraft.subject])
  const recipients = useMemo(() => {
    if (data?.emailThread) {
      return data.emailThread.participants
        .filter(participant => participant.team?.id !== teamId)
        .map(participant => participant.address)
        .join(', ')
    }
    if (emailDraft.selectedContacts) {
      return emailDraft.selectedContacts.filter(notEmpty).join(', ')
    }
    return ''
  }, [data?.emailThread, emailDraft.selectedContacts, teamId])

  return (
    <Card
      interactive
      onClick={() => onClick(data?.emailThread)}
      style={{
        background: isSelected ? 'rgba(45, 114, 210, 0.2)' : undefined,
        display: 'flex',
        justifyContent: 'space-between',
        gap: '0.25rem',
      }}
    >
      <div className={cx(Classes.SECTION_HEADER_LEFT, ellipsized)}>
        <div className={ellipsized}>
          {recipients && (
            <div className={ellipsized}>
              <span
                style={{
                  fontStyle: 'italic',
                }}
              >
                {'to: '}
              </span>
              {recipients}
            </div>
          )}
          <h6
            className={cx(
              Classes.HEADING,
              Classes.SECTION_HEADER_TITLE,
              ellipsized
            )}
          >
            {emailDraft.fileId && (
              <Icon
                icon='paperclip'
                className={Classes.TEXT_MUTED}
                style={{ paddingRight: '0.25em' }}
              />
            )}
            {subject}
          </h6>
          {emailDraft.content}
        </div>
      </div>
      <div className={Classes.SECTION_HEADER_RIGHT}>
        <Icon icon='chevron-right' className={Classes.TEXT_MUTED} />
      </div>
    </Card>
  )
}
export default DraftLogCard
