import InstructorQuestionnaire from '@/instructor/InstructorQuestionnaire'
import { useNavigate, useParams } from '@/router'
import { Button, Classes, Icon } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetTeamQuestionnaireState } from '@inject/graphql/queries'
import Container from '@inject/shared/components/Container'
import Message from '@inject/shared/components/Message'
import HeaderItem from '@inject/shared/components/Message/HeaderItem'
import { createPortal } from 'react-dom'

const wrapper = css`
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  height: 100%;
  width: 100%;
`

const title = css`
  font-weight: bold;
`

const Page = () => {
  const { teamId, exerciseId, channelId, formId } = useParams(
    '/instructor/:exerciseId/:teamId/:channelId/form/detail/:formId'
  )
  const nav = useNavigate()
  const [{ data }] = useTypedQuery({
    query: GetTeamQuestionnaireState,
    variables: {
      questionnaireId: formId,
      teamId,
    },
  })
  const elId = document.getElementById('backnavPortal')
  if (!data?.questionnaireState) {
    return <p>Error</p>
  }

  return (
    <Container>
      <div className={wrapper}>
        {elId &&
          createPortal(
            <Button
              icon='chevron-left'
              text='Back'
              minimal
              onClick={() =>
                nav(`/instructor/:exerciseId/:teamId/:channelId/form`, {
                  params: {
                    teamId,
                    exerciseId,
                    channelId,
                  },
                })
              }
            />,
            elId
          )}
        <Message
          fill
          header={
            <HeaderItem>
              <Icon
                className={Classes.TEXT_MUTED}
                style={{ paddingLeft: '0.25rem' }}
                icon='form'
              />
              <span className={title}>
                {data.questionnaireState.questionnaire.title}
              </span>
            </HeaderItem>
          }
        >
          <InstructorQuestionnaire
            content={data.questionnaireState.questionnaire.content}
            questionnaireId={data.questionnaireState.questionnaire.id}
            questions={data.questionnaireState.questionnaire.questions}
            relatedMilestones={data.questionnaireState.relatedMilestones}
            status={data.questionnaireState.status}
            teamAnswers={data.questionnaireState.answers}
            teamId={teamId}
            exerciseId={exerciseId}
          />
        </Message>
      </div>
    </Container>
  )
}

export default Page
