import type { EmailSelection } from '@/analyst/utilities'
import type { LinkType } from '@/components/LinkButton'
import { Divider } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { EmailThread } from '@inject/graphql/fragments/EmailThread.generated'
import type { FC } from 'react'
import { useMemo } from 'react'
import {
  OPEN_COMPOSE_EVENT_TYPE,
  OPEN_REPLY_EVENT_TYPE,
} from '../EmailFormOverlay'
import EmailCard from './EmailCard'
import ThreadHeaderCard from './ThreadHeaderCard'
import Subtitle from './ThreadHeaderCard/Subtitle'
import ThreadLog from './ThreadLog'

const emailThread = css`
  flex: 2;
  display: flex;
  flex-direction: column;
`

const emailCardList = css`
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow-y: auto;
  gap: 1rem;
  padding: 0.5rem 1rem;
`

interface TeamEmailsProps {
  exerciseId: string
  teamId: string
  emailThreads: EmailThread[]
  selectedTab: EmailSelection
  receivedLink: LinkType
  sentLink: LinkType
  draftsLink?: LinkType
  selectedEmailThread: EmailThread | undefined
  onClick: (emailThread: EmailThread) => void
  inAnalyst?: boolean
  allowComposing: boolean
  composeButtonTitle?: string
  allowReplying: boolean
  replyButtonTitle?: string
  inInstructor?: boolean
  allowForwarding: boolean
  forwardButtonTitle?: string
}

const TeamEmails: FC<TeamEmailsProps> = ({
  exerciseId,
  teamId,
  emailThreads,
  selectedTab,
  receivedLink,
  sentLink,
  draftsLink,
  selectedEmailThread,
  onClick,
  inAnalyst = false,
  allowComposing,
  composeButtonTitle,
  allowReplying,
  replyButtonTitle,
  inInstructor = false,
  allowForwarding,
  forwardButtonTitle,
}) => {
  const emails = useMemo(
    () =>
      [
        ...(selectedEmailThread?.emails.map(email => ({
          ...email,
          subject: selectedEmailThread.subject,
          to: selectedEmailThread.participants
            .filter(participant => participant.address !== email.sender.address)
            .map(participant => participant.address)
            .join(', '),
        })) || []),
      ].reverse(),
    [selectedEmailThread]
  )

  return (
    <>
      <div
        style={{
          display: 'flex',
          height: '100%',
        }}
      >
        <ThreadLog
          emailThreads={emailThreads}
          teamId={teamId}
          selectedTab={selectedTab}
          receivedLink={receivedLink}
          sentLink={sentLink}
          draftsLink={draftsLink}
          selectedEmailThreadId={selectedEmailThread?.id}
          onClick={onClick}
          inInstructor={inInstructor}
          inAnalyst={inAnalyst}
          allowComposing={allowComposing}
          composeButtonTitle={composeButtonTitle}
          onCompose={() =>
            window.dispatchEvent(new Event(OPEN_COMPOSE_EVENT_TYPE))
          }
        />

        {selectedEmailThread ? (
          <div className={emailThread}>
            <ThreadHeaderCard
              title={selectedEmailThread.subject}
              subtitle={
                <Subtitle
                  participants={selectedEmailThread.participants}
                  showDescription={inInstructor || inAnalyst}
                />
              }
              allowReplying={allowReplying}
              replyButtonTitle={replyButtonTitle}
              onReply={() =>
                window.dispatchEvent(
                  new CustomEvent(OPEN_REPLY_EVENT_TYPE, {
                    detail: { emailThread: selectedEmailThread },
                  })
                )
              }
            />
            <Divider />
            <div className={emailCardList}>
              {emails.map(email => (
                <EmailCard
                  key={email.id}
                  exerciseId={exerciseId}
                  teamId={teamId}
                  email={email}
                  inAnalyst={inAnalyst}
                  inInstructor={inInstructor}
                  allowForwarding={allowForwarding}
                  forwardButtonTitle={forwardButtonTitle}
                  subject={email.subject}
                  to={email.to}
                />
              ))}
            </div>
          </div>
        ) : (
          <div />
        )}
      </div>
    </>
  )
}

export default TeamEmails
