import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import dayjs from "dayjs";
import { useRef, useState, useEffect } from "react";
import { useUncontrolledDates } from "../../hooks/use-uncontrolled-dates/use-uncontrolled-dates.mjs";
import { useDatesContext } from "../DatesProvider/use-dates-context.mjs";
import { assignTime } from "../../utils/assign-time/assign-time.mjs";
import { Calendar } from "../Calendar/Calendar.mjs";
import { pickCalendarProps } from "../Calendar/pick-calendar-levels-props/pick-calendar-levels-props.mjs";
import { HiddenDatesInput } from "../HiddenDatesInput/HiddenDatesInput.mjs";
import { dateStringParser } from "./date-string-parser/date-string-parser.mjs";
import { isDateValid } from "./is-date-valid/is-date-valid.mjs";
import { factory } from "../../../../../../../@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/factory/factory.mjs";
import { useInputProps } from "../../../../../../../@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Input/use-input-props.mjs";
import { CloseButton } from "../../../../../../../@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/CloseButton/CloseButton.mjs";
import { useDidUpdate } from "../../../../../../../@mantine_hooks@7.15.2_react@18.3.1/node_modules/@mantine/hooks/esm/use-did-update/use-did-update.mjs";
import { useClickOutside } from "../../../../../../../@mantine_hooks@7.15.2_react@18.3.1/node_modules/@mantine/hooks/esm/use-click-outside/use-click-outside.mjs";
import { Input } from "../../../../../../../@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Input/Input.mjs";
import { Popover } from "../../../../../../../@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Popover/Popover.mjs";
const defaultProps = {
  valueFormat: "MMMM D, YYYY",
  fixOnBlur: true,
  preserveTime: true
};
const DateInput = factory((_props, ref) => {
  const props = useInputProps("DateInput", defaultProps, _props);
  const {
    inputProps,
    wrapperProps,
    value,
    defaultValue,
    onChange,
    clearable,
    clearButtonProps,
    popoverProps,
    getDayProps,
    locale,
    valueFormat,
    dateParser,
    minDate,
    maxDate,
    fixOnBlur,
    onFocus,
    onBlur,
    onClick,
    readOnly,
    name,
    form,
    rightSection,
    unstyled,
    classNames,
    styles,
    allowDeselect,
    preserveTime,
    date,
    defaultDate,
    onDateChange,
    ...rest
  } = props;
  const _wrapperRef = useRef(null);
  const _dropdownRef = useRef(null);
  const [dropdownOpened, setDropdownOpened] = useState(false);
  const { calendarProps, others } = pickCalendarProps(rest);
  const ctx = useDatesContext();
  const defaultDateParser = (val) => {
    const parsedDate = dayjs(val, valueFormat, ctx.getLocale(locale)).toDate();
    return Number.isNaN(parsedDate.getTime()) ? dateStringParser(val, ctx.getTimezone()) : parsedDate;
  };
  const _dateParser = dateParser || defaultDateParser;
  const _allowDeselect = allowDeselect !== void 0 ? allowDeselect : clearable;
  const formatValue = (val) => val ? dayjs(val).locale(ctx.getLocale(locale)).format(valueFormat) : "";
  const [_value, setValue, controlled] = useUncontrolledDates({
    type: "default",
    value,
    defaultValue,
    onChange
  });
  const [_date, setDate] = useUncontrolledDates({
    type: "default",
    value: date,
    defaultValue: defaultValue || defaultDate,
    onChange: onDateChange
  });
  useEffect(() => {
    if (controlled && value !== null) {
      setDate(value);
    }
  }, [controlled, value]);
  const [inputValue, setInputValue] = useState(formatValue(_value));
  useEffect(() => {
    setInputValue(formatValue(_value));
  }, [ctx.getLocale(locale)]);
  const handleInputChange = (event) => {
    const val = event.currentTarget.value;
    setInputValue(val);
    setDropdownOpened(true);
    if (val.trim() === "" && clearable) {
      setValue(null);
    } else {
      const dateValue = _dateParser(val);
      if (isDateValid({ date: dateValue, minDate, maxDate })) {
        setValue(dateValue);
        setDate(dateValue);
      }
    }
  };
  const handleInputBlur = (event) => {
    onBlur == null ? void 0 : onBlur(event);
    setDropdownOpened(false);
    fixOnBlur && setInputValue(formatValue(_value));
  };
  const handleInputFocus = (event) => {
    onFocus == null ? void 0 : onFocus(event);
    setDropdownOpened(true);
  };
  const handleInputClick = (event) => {
    onClick == null ? void 0 : onClick(event);
    setDropdownOpened(true);
  };
  const _getDayProps = (day) => ({
    ...getDayProps == null ? void 0 : getDayProps(day),
    selected: dayjs(_value).isSame(day, "day"),
    onClick: (event) => {
      var _a, _b;
      (_b = getDayProps == null ? void 0 : (_a = getDayProps(day)).onClick) == null ? void 0 : _b.call(_a, event);
      const valueWithTime = preserveTime ? assignTime(_value, day) : day;
      const val = clearable && _allowDeselect ? dayjs(_value).isSame(day, "day") ? null : valueWithTime : valueWithTime;
      setValue(val);
      !controlled && setInputValue(formatValue(val));
      setDropdownOpened(false);
    }
  });
  const _rightSection = rightSection || (clearable && _value && !readOnly ? /* @__PURE__ */ jsx(
    CloseButton,
    {
      variant: "transparent",
      onMouseDown: (event) => event.preventDefault(),
      tabIndex: -1,
      onClick: () => {
        setValue(null);
        !controlled && setInputValue("");
        setDropdownOpened(false);
      },
      unstyled,
      size: inputProps.size || "sm",
      ...clearButtonProps
    }
  ) : null);
  useDidUpdate(() => {
    _value !== void 0 && !dropdownOpened && setInputValue(formatValue(_value));
  }, [_value]);
  useClickOutside(() => setDropdownOpened(false), void 0, [
    _wrapperRef.current,
    _dropdownRef.current
  ]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Input.Wrapper, { ...wrapperProps, __staticSelector: "DateInput", ref: _wrapperRef, children: /* @__PURE__ */ jsxs(
      Popover,
      {
        opened: dropdownOpened,
        trapFocus: false,
        position: "bottom-start",
        disabled: readOnly,
        withRoles: false,
        unstyled,
        ...popoverProps,
        children: [
          /* @__PURE__ */ jsx(Popover.Target, { children: /* @__PURE__ */ jsx(
            Input,
            {
              "data-dates-input": true,
              "data-read-only": readOnly || void 0,
              autoComplete: "off",
              ref,
              value: inputValue,
              onChange: handleInputChange,
              onBlur: handleInputBlur,
              onFocus: handleInputFocus,
              onClick: handleInputClick,
              readOnly,
              rightSection: _rightSection,
              ...inputProps,
              ...others,
              __staticSelector: "DateInput"
            }
          ) }),
          /* @__PURE__ */ jsx(
            Popover.Dropdown,
            {
              onMouseDown: (event) => event.preventDefault(),
              "data-dates-dropdown": true,
              ref: _dropdownRef,
              children: /* @__PURE__ */ jsx(
                Calendar,
                {
                  __staticSelector: "DateInput",
                  __timezoneApplied: true,
                  ...calendarProps,
                  classNames,
                  styles,
                  unstyled,
                  __preventFocus: true,
                  minDate,
                  maxDate,
                  locale,
                  getDayProps: _getDayProps,
                  size: inputProps.size,
                  date: _date,
                  onDateChange: setDate
                }
              )
            }
          )
        ]
      }
    ) }),
    /* @__PURE__ */ jsx(HiddenDatesInput, { name, form, value: _value, type: "default" })
  ] });
});
DateInput.classes = { ...Input.classes, ...Calendar.classes };
DateInput.displayName = "@mantine/dates/DateInput";
export {
  DateInput
};
