
import type { InputBaseProps } from '@material-ui/core/InputBase'
import { useTheme } from '@material-ui/core/styles'
import TextFieldMui, {
  OutlinedTextFieldProps as MuiTextFieldProps,
} from '@material-ui/core/TextField'
import React, { FC } from 'react'
import type { FieldRenderProps } from 'react-final-form'
import type { FieldProps } from './Field'

export type TextFieldHTMLElement = HTMLInputElement | HTMLTextAreaElement

export type TextFieldProps = Omit<MuiTextFieldProps, 'variant'> &
  FieldProps<TextFieldHTMLElement> &
  Pick<InputBaseProps, 'endAdornment' | 'startAdornment'>

type RenderTextFieldProps = TextFieldProps &
  FieldRenderProps<any, TextFieldHTMLElement>

export const TextFieldBase: FC<RenderTextFieldProps> = ({
  input: { name, ...restInput },
  meta: { submitError, dirtySinceLastSubmit, error, touched },
  label,
  rows,
  helperText,
  type,
  placeholder,
  // required,
  endAdornment,
  startAdornment,
  name: ignore,
  ...rest
}) => {
  const showError = ((submitError && !dirtySinceLastSubmit) || error) && touched
  const theme = useTheme()
  return (
    <TextFieldMui
      name={name}
      error={showError}
      type={type}
      label={label}
      placeholder={placeholder}
      helperText={
        (showError && (submitError || error)) || helperText || <span />
      }
      style={helperText ? { marginBottom: theme.spacing(3) } : undefined}
      InputLabelProps={label && placeholder ? { shrink: true } : undefined}
      InputProps={{
        endAdornment,
        startAdornment,
      }}
      margin={'dense'}
      fullWidth={type !== 'number'}
      multiline={!!rows}
      rows={rows}
      variant="outlined"
      {...restInput}
      {...rest}
    />
  )
}
