import { EmailSelection } from '@/analyst/utilities'
import InstructorTeamEmails from '@/email/TeamEmails/InstructorTeamEmails'
import { useNavigate, useParams } from '@/router'
import { css } from '@emotion/css'
import { useGetEmailThreadsSuspenseQuery } from '@inject/graphql/queries/GetEmailThreads.generated'
import notEmpty from '@inject/shared/utils/notEmpty'

const page = css`
  height: 100%;
`

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

  const { data: emailThreadsData } = useGetEmailThreadsSuspenseQuery({
    variables: { teamId },
  })

  return (
    <div className={page}>
      <InstructorTeamEmails
        exerciseId={exerciseId}
        teamId={teamId}
        emailThreads={emailThreadsData?.emailThreads?.filter(notEmpty) || []}
        selectedTab={tab ? (tab as EmailSelection) : EmailSelection.SENT}
        receivedLink={[
          '/instructor/:exerciseId/:teamId/:channelId/email/:tab',
          {
            params: {
              exerciseId,
              teamId,
              channelId,
              tab: EmailSelection.RECEIVED,
            },
          },
        ]}
        sentLink={[
          '/instructor/:exerciseId/:teamId/:channelId/email/:tab',
          {
            params: { exerciseId, teamId, channelId, tab: EmailSelection.SENT },
          },
        ]}
        draftsLink={[
          '/instructor/:exerciseId/:teamId/:channelId/email/:tab',
          {
            params: {
              exerciseId,
              teamId,
              channelId,
              tab: EmailSelection.DRAFTS,
            },
          },
        ]}
        selectedEmailThreadId={threadId ? threadId : undefined}
        onClick={emailThread =>
          nav(
            '/instructor/:exerciseId/:teamId/:channelId/email/:tab/:threadId',
            {
              params: {
                exerciseId,
                teamId,
                tab,
                channelId,
                threadId: emailThread.id,
              },
            }
          )
        }
      />
    </div>
  )
}

export default Layout
