import TooltipLabel from '@/editor/Tooltips/TooltipLabel'
import { QUESTIONNAIRE_QUESTION_FORM } from '@/editor/assets/pageContent/injectSpecification'
import { Button, Colors, Icon, InputGroup, Intent } from '@blueprintjs/core'
import type { FC } from 'react'
import { memo, useCallback, useEffect, useState } from 'react'

interface CustomLabelFormProps {
  onAdd: (value: string) => void
}

const CustomLabelForm: FC<CustomLabelFormProps> = ({ onAdd }) => {
  const [newAnswer, setNewAnswer] = useState<string>('')
  const [isValid, setIsValid] = useState<boolean>(true)

  useEffect(() => {
    setIsValid(!newAnswer.includes(','))
  }, [newAnswer])

  const onAddClick = useCallback(
    (answer: string) => {
      onAdd(answer)
      setNewAnswer('')
    },
    [onAdd]
  )

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'end' }}>
        <TooltipLabel
          label={QUESTIONNAIRE_QUESTION_FORM.newAnswer}
          style={{ flexGrow: '1', marginBottom: '0' }}
        >
          <InputGroup
            placeholder='Input text'
            value={newAnswer}
            onChange={e => setNewAnswer(e.target.value)}
            intent={isValid ? Intent.NONE : Intent.DANGER}
          />
        </TooltipLabel>
        <Button
          icon='plus'
          minimal
          onClick={() => onAddClick(newAnswer)}
          disabled={!isValid}
        />
      </div>
      {!isValid && (
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            padding: '0.5rem 0',
            color: Colors.RED3,
          }}
        >
          <Icon
            icon='error'
            intent='danger'
            style={{ marginRight: '0.5rem' }}
          />
          <span>The answer cannot contain &apos;,&apos;.</span>
        </div>
      )}
    </div>
  )
}

export default memo(CustomLabelForm)
