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 { 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 } = useParams(
    '/analyst/:exerciseId/emails/:threadId'
  )

  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) {
    return <NonIdealState title='Select a thread to view' />
  }

  return (
    <div className={emailThread}>
      <ThreadHeaderCard
        allowForwarding={false}
        allowReplying={false}
        emails={emails}
        subject={selectedEmailThread.subject}
        title={selectedEmailThread.subject}
        subtitle={
          <Subtitle
            participants={selectedEmailThread.participants}
            showDescription
          />
        }
      />
      <Divider />
      <div className={emailCardList}>
        {emails.map(email => (
          <EmailCard
            key={email.id}
            exerciseId={exerciseId}
            teamId={'0'}
            email={email}
            inInstructor
          />
        ))}
      </div>
    </div>
  )
}

export default Page
