import {
  convertToDateFormat,
  isValidDate
} from "./chunk-CI5GCPUG.js";
import {
  TextField
} from "./chunk-6RDK3FM2.js";
import {
  mergeRefs
} from "./chunk-QGGILW3D.js";

// src/components/DateField/DateField.tsx
import classNames from "classnames/dedupe";
import { useEffect, useRef, useState } from "react";
import { jsx } from "react/jsx-runtime";
var MIN_MAX_ERROR = '"min" value should not be greater than "max" value.';
var DateField = ({ ref, ...props }) => {
  const {
    min,
    max,
    format,
    className,
    errorMessage,
    defaultValue,
    value,
    ...otherProps
  } = props;
  const [error, setError] = useState(errorMessage);
  const [isInvalid, setIsInvalid] = useState(void 0);
  const localRef = useRef(null);
  const classes = classNames("mobius-date-field", className);
  const formattedMin = min ? convertToDateFormat(min, format) : void 0;
  const formattedMax = max ? convertToDateFormat(max, format) : void 0;
  const formattedDefaultValue = defaultValue ? convertToDateFormat(defaultValue, format) : void 0;
  const formattedValue = value ? convertToDateFormat(value, format) : void 0;
  const setInvalidState = (error2) => {
    setError(error2);
    setIsInvalid(true);
  };
  const setValidState = () => {
    setError(props.errorMessage);
    setIsInvalid(false);
  };
  useEffect(() => {
    if (!isValidDate(min, format)) {
      setInvalidState(`Invalid min date: ${min}`);
      return;
    }
    if (!isValidDate(max, format)) {
      setInvalidState(`Invalid max date: ${max}`);
      return;
    }
    if (min && max) {
      const minDate = new Date(min);
      const maxDate = new Date(max);
      if (minDate > maxDate) {
        setInvalidState(MIN_MAX_ERROR);
      } else {
        setValidState();
      }
    } else {
      setValidState();
    }
  }, [min, max, format]);
  const validate = () => {
    const isValidInput = localRef.current?.checkValidity();
    if (!isValidInput) {
      setInvalidState("Invalid date input");
    } else {
      setValidState();
    }
  };
  const handleBlur = (event) => {
    validate();
    otherProps.onBlur?.(event);
  };
  return /* @__PURE__ */ jsx(
    TextField,
    {
      ref: mergeRefs([localRef, ref]),
      className: classes,
      type: "date",
      min: formattedMin,
      max: formattedMax,
      errorMessage: errorMessage ?? error,
      isInvalid,
      defaultValue: formattedDefaultValue,
      value: formattedValue,
      onBlur: handleBlur,
      ...otherProps
    }
  );
};
DateField.displayName = "DateField";

export {
  MIN_MAX_ERROR,
  DateField
};
//# sourceMappingURL=chunk-5QMKPWB4.js.map
