import { EmailSelection } from '@/analyst/utilities'
import { OPEN_REPLY_EVENT_TYPE } from '@/email/EmailFormOverlay'
import EmailCard from '@/email/TeamEmails/EmailCard'
import ThreadHeaderCard from '@/email/TeamEmails/ThreadHeaderCard'
import Subtitle from '@/email/TeamEmails/ThreadHeaderCard/Subtitle'
import type { ExtendedEmail } from '@/email/typing'
import { useParams } from '@/router'
import { Divider, NonIdealState } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetEmailThread } from '@inject/graphql/queries'
import { useLoopStatus } from '@inject/graphql/utils/useExerciseLoopStatusSubscription'
import { useMemo } from 'react'

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

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

const Page = () => {
  const { threadId, exerciseId, teamId, tab } = useParams(
    '/trainee/:exerciseId/:teamId/email/:tab/:threadId'
  )

  const { running } = useLoopStatus()
  const [{ data }] = useTypedQuery({
    query: GetEmailThread,
    variables: {
      threadId,
    },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  const selectedEmailThread = data?.emailThread
  const emails: ExtendedEmail[] = useMemo(
    () => [
      ...(selectedEmailThread?.emails.map(email => ({
        ...email,
        subject: selectedEmailThread.subject,
        to: selectedEmailThread.participants
          .filter(participant => participant.address !== email.sender.address)
          .map(participant => participant.address)
          .join(', '),
      })) || []),
    ],
    [selectedEmailThread]
  )

  if (
    !selectedEmailThread ||
    selectedEmailThread.archived !== (tab === EmailSelection.ARCHIVED)
  ) {
    return <NonIdealState title='Select a thread to view' />
  }

  return (
    <div className={emailThread}>
      <ThreadHeaderCard
        emails={emails}
        subject={selectedEmailThread.subject}
        title={selectedEmailThread.subject}
        subtitle={<Subtitle participants={selectedEmailThread.participants} />}
        allowForwarding={running}
        forwardButtonTitle={
          !running ? 'The exercise had been stopped' : undefined
        }
        allowReplying={running}
        replyButtonTitle={
          !running ? 'The exercise had been stopped' : undefined
        }
        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}
            allowForwarding={running}
            forwardButtonTitle={
              !running ? 'The exercise had been stopped' : undefined
            }
            inInstructor={false}
          />
        ))}
      </div>
    </div>
  )
}

export default Page
