import { Button, Callout, InputGroup } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Tool } from '@inject/graphql/fragment-types'
import type { VariablesOf } from '@inject/graphql/graphql'
import { PerformTeamToolAction } from '@inject/graphql/mutations'
import { breakWord } from '@inject/shared/css/textOverflow'
import type { FC, KeyboardEventHandler } from 'react'
import { useState } from 'react'
import { useClient } from 'urql'

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 client = useClient()
  const { tooltipDescription, id } = grapheneTool
  const [value, setValue] = useState<string>('')

  const mutateData = () => {
    if (value.trim() === '') {
      return
    }
    client
      .mutation<unknown, VariablesOf<typeof PerformTeamToolAction>>(
        PerformTeamToolAction,
        {
          teamId,
          toolId: id || 'none',
          toolArgument: value.trim(),
        }
      )
      .toPromise()
    setOpen(false)
    setValue('')
  }
  const handleEnter: KeyboardEventHandler<HTMLInputElement> = e => {
    if (e.key === 'Enter') mutateData()
  }

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

export default GrapheneForm
