import { EmailSelection } from '@/analyst/utilities'
import {
  OPEN_COMPOSE_EVENT_TYPE,
  OPEN_REPLY_EVENT_TYPE,
} from '@/email/EmailFormOverlay'
import getExtendedEmailThreads from '@/email/TeamEmails/getExtendedEmailThreads'
import DraftLogCards from '@/email/TeamEmails/ThreadLog/DraftLogCards'
import ThreadLogCards, {
  selectionStringify,
} from '@/email/TeamEmails/ThreadLog/ThreadLogCards'
import { useNavigate, useParams } from '@/router'
import { Colors } from '@blueprintjs/colors'
import { css } from '@emotion/css'
import type { ResultOf, VariablesOf } from '@inject/graphql/graphql'
import { useTypedQuery } from '@inject/graphql/graphql'
import { setIsUnreadChannel } from '@inject/graphql/mutations.client'
import { GetEmailThreads, GetExerciseChannels } from '@inject/graphql/queries'
import { useEffect, useMemo } from 'react'
import { Outlet } from 'react-router-dom'
import { useClient } from 'urql'

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

  const [{ data: emailThreadsData }] = useTypedQuery({
    query: GetEmailThreads,
    variables: {
      teamId,
      received: tab === EmailSelection.RECEIVED,
      sent: tab === EmailSelection.SENT,
      archived: tab === EmailSelection.ARCHIVED,
    },
    pause: tab === EmailSelection.DRAFTS,
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  const client = useClient()
  useEffect(() => {
    if (
      emailThreadsData?.emailThreads.every(thread =>
        thread.emails.every(email => email.readReceipt)
      )
    ) {
      // TODO: remove Email channels from native UI listing, create special EmailChannelButton which tracks the read state there
      client
        .query<
          ResultOf<typeof GetExerciseChannels>,
          VariablesOf<typeof GetExerciseChannels>
        >(GetExerciseChannels, {
          exerciseId,
        })
        .then(({ data }) => {
          const channel = data?.exerciseChannels.find(
            channel => channel.type === 'EMAIL'
          )
          // TODO: simplify isUnread, should be isRead to simplify truthiness
          client
            .mutation<unknown, VariablesOf<typeof setIsUnreadChannel>>(
              setIsUnreadChannel,
              {
                channelId: channel?.id || 'email',
                isUnread: false,
                teamId,
              }
            )
            .then()
        })
    }
  }, [client, emailThreadsData?.emailThreads, exerciseId, teamId])

  const emailThreads = getExtendedEmailThreads({
    emailThreads: emailThreadsData?.emailThreads || [],
    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/email/:tab/:threadId', {
                  params: {
                    exerciseId,
                    teamId,
                    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
