import { Button, Callout, InputGroup } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Tool } from '@inject/graphql/fragments/Tool.generated'
import { usePerformTeamToolAction } from '@inject/graphql/mutations/PerformTeamToolAction.generated'
import type { FC, KeyboardEventHandler } from 'react'
import { useState } from 'react'

const wrapper = css`
  display: flex;
  flex-direction: column;
`

const submit = css`
  margin-top: 0.2rem;
  align-self: flex-end;
`

interface GrapheneFormProps {
  grapheneTool: Tool
  teamId: string
  setOpen(arg0: boolean): void
  disabled?: boolean
  disabledTitle?: string
}

const GrapheneForm: FC<GrapheneFormProps> = ({
  grapheneTool,
  teamId,
  setOpen,
  disabled,
  disabledTitle,
}) => {
  const { tooltipDescription, id } = grapheneTool
  const [mutate] = usePerformTeamToolAction()
  const [value, setValue] = useState<string>('')

  const mutateData = () => {
    if (value.trim() === '') {
      return
    }
    mutate({
      variables: {
        teamId,
        toolId: id || 'none',
        toolArgument: value.trim(),
      },
    })
    setOpen(false)
    setValue('')
  }
  const handleEnter: KeyboardEventHandler<HTMLInputElement> = e => {
    if (e.key === 'Enter') mutateData()
  }

  return (
    <Callout className={wrapper}>
      <p>{tooltipDescription}</p>
      <InputGroup
        placeholder={grapheneTool.hint || 'Argument'}
        value={value}
        onChange={e => setValue(e.currentTarget.value)}
        onKeyDown={handleEnter}
        readOnly={disabled}
        title={disabled ? disabledTitle : undefined}
      />
      <Button
        className={submit}
        outlined
        minimal
        onClick={mutateData}
        disabled={disabled}
        title={disabled ? disabledTitle : undefined}
      >
        Submit
      </Button>
    </Callout>
  )
}

export default GrapheneForm
