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 ToolFormProps {
  tool: Tool
  teamId: string
  setOpen(arg0: boolean): void
  disabled?: boolean
  disabledTitle?: string
}

const ToolForm: FC<ToolFormProps> = ({
  tool,
  teamId,
  setOpen,
  disabled,
  disabledTitle,
}) => {
  const client = useClient()
  const { tooltipDescription, id, requiresInput } = tool
  const [value, setValue] = useState<string>('')

  const mutateData = () => {
    if (requiresInput && 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>
      {requiresInput && (
        <InputGroup
          placeholder={tool.hint || 'Argument'}
          value={value}
          onChange={e => setValue(e.currentTarget.value)}
          onKeyDown={handleEnter}
          readOnly={disabled}
          title={disabled ? disabledTitle : tool.hint || 'Argument'}
        />
      )}
      <Button
        className={submit}
        outlined
        minimal
        onClick={mutateData}
        disabled={disabled}
        title={disabled ? disabledTitle : undefined}
      >
        Submit
      </Button>
    </Callout>
  )
}

export default ToolForm
