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 type { VariablesOf } from '@inject/graphql/graphql'
import { useTypedQuery } from '@inject/graphql/graphql'
import { setIsUnreadEmailThread } from '@inject/graphql/mutations.client'
import { GetEmailThread } from '@inject/graphql/queries'
import { useClient } from '@inject/graphql/urql/client'
import { useEffect, 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(
    '/instructor/:exerciseId/:teamId/:channelId/email/:tab/:threadId'
  )

  const [{ data }] = useTypedQuery({
    query: GetEmailThread,
    variables: {
      threadId,
    },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  const client = useClient()
  useEffect(() => {
    if (
      data?.emailThread.readReceipt.find(
        teamReceipt => teamReceipt.teamId === teamId
      )?.isUnread
    ) {
      client
        .mutation<unknown, VariablesOf<typeof setIsUnreadEmailThread>>(
          setIsUnreadEmailThread,
          {
            threadId,
            isUnread: false,
            teamId,
          }
        )
        .then()
    }
  })
  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.participants.some(
      participant => participant.team?.id === teamId
    ) ||
    selectedEmailThread.archived !== (tab === EmailSelection.ARCHIVED)
  ) {
    return <NonIdealState title='Select a thread to view' />
  }

  const replyDisabled =
    selectedEmailThread !== undefined &&
    !selectedEmailThread.participants.some(
      participant => participant.definitionAddress
    )

  return (
    <div className={emailThread}>
      <ThreadHeaderCard
        allowForwarding
        emails={emails}
        subject={selectedEmailThread.subject}
        title={selectedEmailThread.subject}
        subtitle={
          <Subtitle
            participants={selectedEmailThread.participants}
            showDescription
          />
        }
        allowReplying={!replyDisabled}
        replyButtonTitle={
          replyDisabled ? "You can't reply to emails between teams" : 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
            inInstructor
          />
        ))}
      </div>
    </div>
  )
}

export default Page
