import { Tooltip } from '@blueprintjs/core'
import type { EmailDetails } from '@inject/graphql/fragments/EmailDetails.generated'
import type { Team } from '@inject/graphql/fragments/Team.generated'
import type { FC, SVGProps } from 'react'
import { useContext, useRef } from 'react'
import EmailReceived from '../../assets/email-received.svg?react'
import EmailSent from '../../assets/email-sent.svg?react'
import type { XScale, YScale } from '../Plots/ScatterPlot/types'
import { plotDataElement } from '../utilities'
import EmailTooltip from './EmailTooltip'
import FilterContext from './FilterContext'

interface EmailIconProps {
  team: Team
  emailDetails: EmailDetails
  opacity: number
  onClick: () => void
  xScale: XScale
  yScale: YScale
  dotSize: number
}

const EmailIcon: FC<EmailIconProps> = ({
  team,
  emailDetails,
  opacity,
  onClick,
  xScale,
  yScale,
  dotSize,
}) => {
  const ref = useRef(null)

  const {
    displayEmailThreads,
    displayEmailsSent,
    displayEmailsReceived,
    displayEmailsBetweenTeams,
  } = useContext(FilterContext)

  const nonTeamParticipants = emailDetails.thread.participants.filter(
    participant => !participant.team
  )

  const display = () => {
    if (!displayEmailThreads) return false
    if (
      !displayEmailsSent &&
      emailDetails.sender.address === team.emailAddress?.address
    )
      return false
    if (
      !displayEmailsReceived &&
      emailDetails.sender.address !== team.emailAddress?.address
    )
      return false
    if (!displayEmailsBetweenTeams && nonTeamParticipants.length === 0)
      return false
    return true
  }

  const iconProps: SVGProps<SVGSVGElement> = {
    ref,
    className: plotDataElement,
    width: dotSize,
    height: dotSize,
    x: xScale(new Date(emailDetails.timestamp)) - dotSize / 2,
    y: Number(yScale(team.name)) - dotSize / 2,
    opacity,
    onClick,
    style: { display: display() ? 'initial' : 'none' },
  }

  return (
    <Tooltip
      targetTagName='g'
      content={<EmailTooltip emailDetails={emailDetails} />}
      position='right'
    >
      {emailDetails.sender.address === team.emailAddress?.address ? (
        <EmailSent {...iconProps} />
      ) : (
        <EmailReceived {...iconProps} />
      )}
    </Tooltip>
  )
}

export default EmailIcon
