import { Input as AntdInput, InputProps as AntdInputProps } from 'antd'
import React, { useCallback, useState } from 'react'

import classnames from 'classnames'
import { Paragraph } from 'components/Typography'
import { noop } from 'utils/noop'

import './Input.scss'

export interface InputProps extends AntdInputProps {
  className?: string
  displayedText?: string
  initialValue?: string
  isEnabled?: boolean
  setIsEnabled?: (isEnabled: boolean) => void
  onChange?: React.ChangeEventHandler<HTMLInputElement>
}

export const Input: React.FC<InputProps> = ({
  className = '',
  displayedText = null,
  isEnabled = true,
  initialValue = '',
  setIsEnabled = noop,
  onChange = noop,
  ...props
}) => {
  const [isFieldEnabled, setIsFieldEnabled] = useState(true)
  const [value, setValue] = useState(initialValue)

  const handleEnableEdit = useCallback(() => {
    setIsFieldEnabled(true)
  }, [setIsEnabled])

  const handleChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
    event => {
      const { value } = event.target
      setValue(value)

      onChange(event)
    },
    [onChange, setValue]
  )

  const compositeClasses = React.useMemo(
    () =>
      classnames([
        'input',
        className,
        isEnabled ? '' : 'text--grey4 cursor-pointer m__t--4'
      ]),
    [className]
  )

  return isEnabled ? (
    <AntdInput
      addonBefore={displayedText}
      value={value}
      className={compositeClasses}
      onChange={handleChange}
      {...props}
    />
  ) : (
    <Paragraph
      onClick={handleEnableEdit}
      preset="regular14"
      className={compositeClasses}
    >
      {value}
    </Paragraph>
  )
}
