import { jsxs, jsx } from 'react/jsx-runtime';
import { DatePicker } from '../../date-picker.mjs';
import { FormItem, FormControl, FormMessage } from '../../form.mjs';
import AutoFormLabel from '../common/label.mjs';
import AutoFormTooltip from '../common/tooltip.mjs';
import { getBaseType } from '../helpers.mjs';

function toDate(value) {
  if (!value) return void 0;
  if (value instanceof Date) return value;
  if (typeof value === "string") {
    const date = new Date(value);
    return isNaN(date.getTime()) ? void 0 : date;
  }
  return void 0;
}
function AutoFormDate({
  label,
  isRequired,
  field,
  fieldConfigItem,
  fieldProps,
  zodItem
}) {
  const baseType = getBaseType(zodItem);
  const expectsDateObject = baseType === "ZodDate";
  const handleChange = (date) => {
    if (!date) {
      field.onChange(void 0);
      return;
    }
    if (expectsDateObject) {
      field.onChange(date);
    } else {
      field.onChange(date.toISOString());
    }
  };
  return /* @__PURE__ */ jsxs(FormItem, { children: [
    /* @__PURE__ */ jsx(
      AutoFormLabel,
      {
        label: fieldConfigItem?.label || label,
        isRequired
      }
    ),
    /* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(
      DatePicker,
      {
        date: toDate(field.value),
        setDate: handleChange,
        ...fieldProps
      }
    ) }),
    /* @__PURE__ */ jsx(AutoFormTooltip, { fieldConfigItem }),
    /* @__PURE__ */ jsx(FormMessage, {})
  ] });
}

export { AutoFormDate as default };
