import FormControl, { FormControlProps } from '@material-ui/core/FormControl'
import FormHelperText, {
  FormHelperTextProps,
} from '@material-ui/core/FormHelperText'
import InputLabel from '@material-ui/core/InputLabel'
import OutlinedInput from '@material-ui/core/OutlinedInput'
import Select from '@material-ui/core/Select'
import React, { FC } from 'react'
import type { FieldRenderProps } from 'react-final-form'

export interface ISelectStandardProps {
  label: string
  helperText?: string
  formControlProps?: FormControlProps
  formHelperTextProps?: FormHelperTextProps
}

export type SelectHTMLElement = HTMLDivElement

interface ISelectBaseProps
  extends ISelectStandardProps,
    FieldRenderProps<any, SelectHTMLElement> {}

export const SelectFieldBase: FC<ISelectBaseProps> = ({
  input: { name, value, onChange, ...restInput },
  meta: { submitError, dirtySinceLastSubmit, error, touched },
  label,
  helperText: helperTextProp,
  formControlProps = {},
  formHelperTextProps = {},
  ...rest
}) => {
  const inputLabel = React.useRef(null)
  const [labelWidth, setLabelWidth] = React.useState(0)
  React.useEffect(() => {
    // @ts-ignore
    setLabelWidth(inputLabel.current.offsetWidth)
  }, [])
  const showError = ((submitError && !dirtySinceLastSubmit) || error) && touched
  const helperText = (showError && (submitError || error)) ||
    helperTextProp || <span />
  return (
    <FormControl
      variant="outlined"
      {...formControlProps}
      error={showError}
      margin={'dense'}
    >
      <InputLabel ref={inputLabel}>{label}</InputLabel>
      <Select
        value={value}
        onChange={onChange}
        input={
          // @ts-ignore
          <OutlinedInput {...restInput} labelWidth={labelWidth} name={name} />
        }
        {...rest}
      />
      {helperText && (
        <FormHelperText {...formHelperTextProps}>{helperText}</FormHelperText>
      )}
    </FormControl>
  )
}
