import { FC } from 'react';
import { Controller } from 'react-hook-form';

import { SxProps } from '@material-hu/mui/styles';
import TextField from '@material-hu/mui/TextField';

import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';

export type TextFieldControlProps = {
  label: string;
  name: string;
  control?: any;
  placeholder?: string;
  multiline?: boolean;
  isRequired?: boolean;
  sx?: SxProps;
  defaultValue?: string;
  isReadOnly?: boolean;
};

export const TextFieldControl: FC<TextFieldControlProps> = props => {
  const {
    label,
    name,
    control = null,
    placeholder,
    multiline = false,
    isRequired = false,
    defaultValue = '',
    isReadOnly = false,
    sx,
  } = props;

  const { t } = useTranslation();

  return (
    <Controller
      name={name}
      control={control}
      defaultValue={defaultValue}
      rules={{ required: isRequired ? t('REQUIRED_FIELD') : undefined }}
      render={({ field, fieldState: { error } }) => (
        <TextField
          label={isRequired ? `${label} *` : label}
          value={isReadOnly ? defaultValue : field.value}
          placeholder={placeholder}
          onChange={newValue => field.onChange(newValue)}
          sx={{
            mt: 2,
            mb: 1,
            ...sx,
          }}
          error={Boolean(error)}
          helperText={error?.message}
          multiline={multiline}
          disabled={isReadOnly}
          fullWidth
        />
      )}
    />
  );
};

export default TextFieldControl;
