import { Button, Dialog, DialogBody } from '@blueprintjs/core'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExerciseChannels } from '@inject/graphql/queries'
import { dialogBody, maximizedDialog } from '@inject/shared/css/dialog'
import type { FC } from 'react'
import { useState } from 'react'
import InjectForm from './InjectForm'

interface InstructorInjectProps {
  teamId: string | undefined
  exerciseId: string | undefined
  hideLabel?: boolean
}

const InstructorInject: FC<InstructorInjectProps> = ({
  teamId,
  exerciseId,
  hideLabel,
}) => {
  const [isComposerOpen, setIsComposerOpen] = useState(false)

  const [{ data, fetching: loading }] = useTypedQuery({
    query: GetExerciseChannels,
    variables: { exerciseId: exerciseId || '-1' },
    pause: !exerciseId,
  })
  const channelName = data?.exerciseChannels?.find(
    channel => channel?.type === 'INFO'
  )?.displayName

  return (
    <>
      <Button
        loading={loading}
        fill
        minimal
        alignText='left'
        disabled={!teamId || !exerciseId}
        title={
          !teamId || !exerciseId
            ? 'A team has to be selected to send an inject'
            : 'Send an inject'
        }
        icon='annotation'
        text={!hideLabel && 'Send an inject'}
        onClick={() => setIsComposerOpen(!isComposerOpen)}
      />
      {teamId && exerciseId && (
        <Dialog
          className={maximizedDialog}
          canOutsideClickClose={false}
          isOpen={isComposerOpen}
          onClose={() => {
            setIsComposerOpen(false)
          }}
          title={`Send an inject${channelName ? ` into ${channelName}` : ''}`}
          icon='annotation'
        >
          <DialogBody className={dialogBody}>
            <InjectForm
              teamId={teamId}
              exerciseId={exerciseId}
              setIsOpen={setIsComposerOpen}
            />
          </DialogBody>
        </Dialog>
      )}
    </>
  )
}

export default InstructorInject
