import { EmailSelection } from '@/analyst/utilities'
import TraineeTeamEmails from '@/email/TeamEmails/TraineeTeamEmails'
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(
    '/trainee/:exerciseId/:teamId/:channelId/email/:tab/:threadId'
  )
  const nav = useNavigate()

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

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

export default Layout
