import { Button, Dialog, DialogBody } from '@blueprintjs/core'
import { useGetExerciseChannels } from '@inject/graphql/queries/GetExerciseChannels.generated'
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, loading } = useGetExerciseChannels({
    variables: { exerciseId: exerciseId || '-1' },
    skip: !exerciseId,
  })
  const channelName = data?.exerciseChannels?.find(
    channel => channel?.type === 'INFO'
  )?.name

  return (
    <>
      <Button
        active={isComposerOpen}
        loading={loading}
        fill
        minimal
        alignText='left'
        disabled={!teamId || !exerciseId}
        title='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
