import React from 'react';
import TextField from '@mui/material/TextField';

//
// https://developer.mozilla.org/en-US/docs/Web/API/ValidityState
//
const validityStateToString = validity => (
  validity.badInput
    ? 'bad-input'
    : validity.customError
      ? 'custom-error'
      : validity.patternMismatch
        ? 'pattern-missmatch'
        : validity.rangeOverflow
          ? 'range-overflow'
          : validity.rangeUnderflow
            ? 'range-underflow'
            : validity.stepMismatch
              ? 'step-missmatch'
              : validity.tooLong
                ? 'too-long'
                : validity.tooShort
                  ? 'too-short'
                  : validity.typeMismatch
                    ? 'type-missmatch'
                    : validity.valueMissing
                      ? 'value-missing'
                      : !validity.valid
                        ? 'invalid'
                        : null
);

const CustomTextField = ({
  id,
  label,
  type,
  required,
  disabled,
  error,
  helperText,
  value,
  setValue,
  setError,
}) => {
  return (
    <TextField
      id={id}
      label={label}
      type={type}
      required={required}
      disabled={disabled}
      error={!!error}
      helperText={helperText}
      value={value || ''}
      onChange={(event) => {
        const { value, validity } = event.target;
        const validationError = validityStateToString(validity);
        if (validationError) {
          setError({ id: `${validationError}-validation-error` });
        } else {
          setError(undefined);
        }

        setValue(value);
      }}
    />
  );
};

export default CustomTextField;