import { EmailSelection, compareDates } from '@/analyst/utilities'
import { Card, CardList } from '@blueprintjs/core'
import type { Email } from '@inject/graphql/fragments/Email.generated'
import type { EmailThread } from '@inject/graphql/fragments/EmailThread.generated'
import { useMemo, type FC } from 'react'
import ThreadLogCard from './ThreadLogCard'

interface ThreadLogCardsProps {
  teamId: string
  emailThreads: EmailThread[]
  selectedTab: EmailSelection.RECEIVED | EmailSelection.SENT
  selectedEmailThreadId?: string
  onClick: (emailThread: EmailThread) => void
  inAnalyst?: boolean
}

const ThreadLogCards: FC<ThreadLogCardsProps> = ({
  teamId,
  emailThreads,
  selectedTab,
  selectedEmailThreadId,
  onClick,
  inAnalyst = false,
}) => {
  const emailThreadsWithLastEmails = useMemo(
    () =>
      emailThreads
        .reduce<
          {
            emailThread: EmailThread
            lastEmail: Email
          }[]
        >((accumulator, emailThread) => {
          const lastEmail = emailThread.emails
            .filter(email =>
              selectedTab === EmailSelection.RECEIVED
                ? email.sender.team?.id !== teamId
                : email.sender.team?.id === teamId
            )
            .sort(
              (a, b) =>
                -compareDates(new Date(a.timestamp), new Date(b.timestamp))
            )
            .at(0)

          if (lastEmail) {
            accumulator.push({
              emailThread,
              lastEmail,
            })
          }

          return accumulator
        }, [])
        .sort(
          (a, b) =>
            -compareDates(
              new Date(a.lastEmail.timestamp),
              new Date(b.lastEmail.timestamp)
            )
        ),
    [emailThreads, selectedTab, teamId]
  )

  return (
    <CardList bordered={false}>
      {emailThreadsWithLastEmails.length > 0 ? (
        emailThreadsWithLastEmails.map(element => (
          <ThreadLogCard
            key={element.emailThread.id}
            emailThread={element.emailThread}
            lastEmail={element.lastEmail}
            teamId={teamId}
            isSelected={element.emailThread.id === selectedEmailThreadId}
            onClick={() => onClick(element.emailThread)}
            inAnalyst={inAnalyst}
          />
        ))
      ) : (
        <Card>{`No emails${
          selectedTab === undefined
            ? ''
            : ` ${selectedTab === EmailSelection.SENT ? 'sent' : 'received'}`
        }`}</Card>
      )}
    </CardList>
  )
}

export default ThreadLogCards
