import { EmailSelection } from '@/analyst/utilities'
import {
  OPEN_COMPOSE_EVENT_TYPE,
  OPEN_REPLY_EVENT_TYPE,
} from '@/email/EmailFormOverlay'
import getLastEmail from '@/email/TeamEmails/getLastEmail'
import DraftLogCards from '@/email/TeamEmails/ThreadLog/DraftLogCards'
import ThreadLogCards, {
  selectionStringify,
} from '@/email/TeamEmails/ThreadLog/ThreadLogCards'
import type { ExtendedEmaiLThread } from '@/email/TeamEmails/ThreadLog/typing'
import { useNavigate, useParams } from '@/router'
import { Colors } from '@blueprintjs/colors'
import { css } from '@emotion/css'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetEmailThreads } from '@inject/graphql/queries'
import { useMemo } from 'react'
import { Outlet } from 'react-router-dom'

const Page = () => {
  const {
    exerciseId,
    teamId,
    channelId,
    tab: tabUntyped,
    threadId,
  } = useParams(
    '/instructor/:exerciseId/:teamId/:channelId/email/:tab/:threadId'
  )
  const tab = tabUntyped as EmailSelection
  const nav = useNavigate()

  const [{ data: emailThreadsData }] = useTypedQuery({
    query: GetEmailThreads,
    variables: {
      teamId,
      received: tab === EmailSelection.SENT,
      sent: tab === EmailSelection.RECEIVED,
      archived: tab === EmailSelection.ARCHIVED,
    },
    pause: tab === EmailSelection.DRAFTS,
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  //@ts-ignore
  const emailThreads: ExtendedEmaiLThread[] =
    emailThreadsData?.emailThreads.map(thread => ({
      ...thread,
      lastEmail: getLastEmail(thread, teamId, tab),
    })) || []

  switch (tab) {
    case EmailSelection.DRAFTS:
      return (
        <DraftLogCards
          onClick={emailThread => {
            if (emailThread) {
              window.dispatchEvent(
                new CustomEvent(OPEN_REPLY_EVENT_TYPE, {
                  detail: {
                    emailThread,
                  },
                })
              )
            } else {
              window.dispatchEvent(new CustomEvent(OPEN_COMPOSE_EVENT_TYPE))
            }
          }}
          inInstructor
          teamId={teamId}
          selectedEmailThreadId={threadId}
        />
      )
    case EmailSelection.RECEIVED:
    case EmailSelection.ARCHIVED:
    case EmailSelection.SENT:
      return (
        <div
          className={css`
            display: grid;
            height: calc(100vh - 52px);
            grid-template-columns: min(400px, 50%) auto;
            @media only screen and (max-width: 960px) {
              display: block;
              ${threadId
                ? `
                #showLeft {
                  display: none
                }
              `
                : `
                #showRight {
                  display: none;
                }
              `}
            }
          `}
        >
          <div
            id='showLeft'
            className={css`
              overflow-y: auto;
              @media only screen and (min-width: 960.02px) {
                padding-right: 0.5rem;
                border-right: 1px solid ${Colors.BLACK}26;
                .bp5-dark & {
                  border-right-color: ${Colors.WHITE}33;
                }
              }
            `}
          >
            <ThreadLogCards
              teamId={teamId}
              emailThreads={emailThreads}
              noEmailString={selectionStringify(tab)}
              onClick={emailThread => {
                nav(
                  '/instructor/:exerciseId/:teamId/:channelId/email/:tab/:threadId',
                  {
                    params: {
                      exerciseId,
                      teamId,
                      channelId,
                      threadId: emailThread.id,
                      tab,
                    },
                  }
                )
              }}
              selectedEmailThreadId={threadId}
            />
          </div>
          <div
            id='showRight'
            className={css`
              overflow-y: auto;
            `}
          >
            <Outlet />
          </div>
        </div>
      )
    default:
      throw Error('Unclear')
  }
}

export default Page
