import { useEntityBeforePersist } from "@contember/binding";
import { useRef, useState, useCallback, useEffect } from "react";
const useFieldControl = ({
  fieldMetadata,
  parse,
  format,
  onBlur,
  ...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,
    // ControlValueProps
    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,
    value: format(field.current.value, field.current),
    // ControlConstraintProps
    max: format(props.max, field.current),
    maxLength: props.maxLength,
    min: format(props.min, field.current),
    minLength: props.minLength,
    pattern: props.pattern,
    step: props.step,
    // ValidationStateProps
    validationState: field.current.errors ? "invalid" : void 0,
    onValidationStateChange: useCallback((error) => {
      if (field.current.isTouched) {
        setWasTouched(true);
      }
      setValidationError(error);
    }, [field]),
    // ControlStateProps
    active: props.active,
    readOnly: props.readOnly || fieldMetadata.isMutating,
    disabled: props.disabled || fieldMetadata.isMutating,
    loading: fieldMetadata.isMutating,
    required: props.required,
    // TODO: ?? fieldMetadata.field.schema.required,
    notNull: props.notNull ?? fieldMetadata.field.schema.nullable === false,
    focused: props.focused,
    hovered: props.hovered,
    // ControlFocusProps
    onBlur: useCallback(() => {
      setWasTouched(true);
      onBlur?.();
    }, [setWasTouched, onBlur]),
    onFocus: props.onFocus,
    onFocusChange: props.onFocusChange,
    // ControlDisplayProps
    id: props.id,
    className: props.className,
    distinction: props.distinction,
    intent: props.intent,
    scheme: props.scheme,
    size: props.size,
    style: props.style
  };
};
export {
  useFieldControl
};
//# sourceMappingURL=useFieldControl.js.map
