import { TextInput } from '@/components/ra-inputs/TextInput';
import { TextInputProps, maxLength as maxLengthValidator, useTranslate } from 'react-admin';
import { useController } from 'react-hook-form';

type SmartTextInputProps = {
  maxLength?: number;
} & TextInputProps;

function SmartTextInput({ multiline = false, ...props }: SmartTextInputProps): JSX.Element {
  const translate = useTranslate();
  const validationFn = maxLengthValidator(props?.maxLength, 'app.input.max_length_error');
  const value = useController({ name: props?.source })?.field?.value;

  let helperText = props.helperText;
  let validate = props.validate;

  if (!validate) {
    validate = [validationFn];
  } else if (Array.isArray(validate)) {
    if (validate.indexOf(validationFn) === -1) {
      validate.push(validationFn);
    }
  }

  const usedCharsInfo = translate('app.input.max_length_info', {
    count: value?.length || 0,
    max: props?.maxLength
  });

  if (props?.maxLength) {
    helperText =
      helperText && (helperText as string).length > 0
        ? `${usedCharsInfo} - ${translate(helperText as string)}`
        : usedCharsInfo;
  }

  return (
    <TextInput
      {...props}
      validate={validate}
      helperText={helperText}
      multiline={multiline}
      inputProps={{
        maxLength: props?.maxLength
      }}
    />
  );
}

export { SmartTextInput };
export type { SmartTextInputProps };
