import { useEntityBeforePersist } from "@contember/binding";
import { useRef, useState, useCallback, useEffect } from "react";
const useFieldControl = ({
  fieldMetadata,
  parse,
  format,
  ...props
}) => {
  const ref = useRef();
  const field = useRef(fieldMetadata.field);
  field.current = fieldMetadata.field;
  const [validationError, setValidationError] = useState();
  const [wasTouched, setWasTouched] = useState();
  useEntityBeforePersist(useCallback(() => {
    if (validationError) {
      field.current.addError(validationError);
    }
  }, [field, validationError]));
  useEffect(() => {
    if (wasTouched) {
      field.current.clearErrors();
      if (validationError) {
        field.current.addError(validationError);
      }
    }
  }, [validationError, wasTouched]);
  return {
    ref,
    ...props,
    defaultValue: format(field.current.defaultValue, field.current) ?? void 0,
    onChange: useCallback((_value) => {
      const value = parse(_value, field.current) ?? null;
      const valueOrNull = value || value === 0 || value === false ? value : null;
      const isEmptyOnServer = field.current.valueOnServer === null;
      const isStillEmpty = valueOrNull === null;
      field.current.updateValue(isEmptyOnServer && isStillEmpty ? null : value);
    }, [parse]),
    placeholder: props.placeholder,
    name: props.name,
    max: format(props.max, field.current),
    min: format(props.min, field.current),
    value: format(field.current.value, field.current),
    validationState: field.current.errors ? "invalid" : void 0,
    onValidationStateChange: useCallback((error) => {
      if (field.current.isTouched) {
        setWasTouched(true);
      }
      setValidationError(error);
    }, [field]),
    active: props.active,
    readOnly: fieldMetadata.isMutating,
    disabled: fieldMetadata.isMutating,
    loading: fieldMetadata.isMutating,
    required: props.required,
    notNull: props.notNull ?? fieldMetadata.field.schema.nullable === false,
    focused: props.focused,
    hovered: props.hovered,
    onBlur: useCallback(() => {
      setWasTouched(true);
    }, [setWasTouched]),
    onFocus: useCallback(() => {
    }, []),
    onFocusChange: useCallback(() => {
    }, []),
    id: props.id,
    className: props.className,
    distinction: props.distinction,
    intent: props.intent,
    scheme: props.scheme,
    size: props.size
  };
};
export { useFieldControl };
//# sourceMappingURL=useFieldControl.js.map
