import { jsxs, jsx } from 'react/jsx-runtime';
import { forwardRef, useId, useRef, useState, useMemo, useCallback, useEffect, useLayoutEffect } from 'react';
import { Calendar as Calendar$1 } from './primitives/Calendar.js';
import { Popover, PopoverAnchor, PopoverContent } from './primitives/Popover.js';
import { Field, FieldLabel, FieldContent, FieldError, FieldDescription } from './primitives/Field.js';
import { c as cn } from './utils-BJnb9o5c.js';
import { dayjs } from '@bigbinary/neeto-commons-frontend/utils';
import pureDayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { i as isFixedWidthFormat, c as buildRangeMaskTemplate, b as buildMaskTemplate, d as dateToTimeValue, T as TimePickerPanel, a as applyMask } from './TimePickerPanel-SQBEEJko.js';
import { Button } from './primitives/Button.js';
import { c as createLucideIcon } from './createLucideIcon-C8ycilSN.js';
import { X } from './x-_o2T3n6D.js';

/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */


const __iconNode = [
  ["path", { d: "M8 2v4", key: "1cmpym" }],
  ["path", { d: "M16 2v4", key: "4m81vk" }],
  ["rect", { width: "18", height: "18", x: "3", y: "4", rx: "2", key: "1hopcy" }],
  ["path", { d: "M3 10h18", key: "8toen8" }]
];
const Calendar = createLucideIcon("calendar", __iconNode);

const DEFAULT_DATE_FORMAT = "dd/MM/yyyy";
const DEFAULT_TIME_FORMAT = "HH:mm:ss";
const SIZE_CONFIG = {
  small: { trigger: "h-7 text-xs", icon: "size-3.5" },
  medium: { trigger: "h-8 text-sm", icon: "size-4" },
  large: { trigger: "h-10 text-sm", icon: "size-4" }
};

pureDayjs.extend(customParseFormat);
const toBrowserLocalDate = (date) => {
  const d = dayjs(date);
  return new Date(
    d.year(),
    d.month(),
    d.date(),
    d.hour(),
    d.minute(),
    d.second()
  );
};
const toNativeDate = (value) => {
  if (value == null) return null;
  if (value instanceof Date) return value;
  if (typeof value.toDate === "function") {
    return toBrowserLocalDate(value.toDate());
  }
  if (typeof value === "string") {
    const parsed = new Date(value);
    if (!isNaN(parsed.getTime())) return toBrowserLocalDate(parsed);
  }
  return null;
};
const coerceDateValue = (value, type) => {
  if (value == null) return null;
  if (type === "range" && Array.isArray(value)) {
    return [toNativeDate(value[0]), toNativeDate(value[1])];
  }
  return toNativeDate(value);
};
const normalizeToDayjsFormat = (fmt) => fmt.replace(/\byyyy\b/g, "YYYY").replace(/\byy\b/g, "YY").replace(/\bdd\b/g, "DD").replace(/\bd\b/g, "D");
const normalizeToDateFnsFormat = (fmt) => fmt.replace(/YYYY/g, "yyyy").replace(/YY/g, "yy").replace(/DD/g, "dd").replace(/\bD\b/g, "d");
const formatDate = (date, formatStr) => {
  if (!date) return "";
  try {
    return pureDayjs(date).format(normalizeToDayjsFormat(formatStr));
  } catch {
    return "";
  }
};
const parseDate = (str, formatStr) => {
  if (!str) return null;
  const dayjsFmt = normalizeToDayjsFormat(formatStr);
  const parsed = pureDayjs(str, dayjsFmt);
  if (parsed.isValid()) return parsed.toDate();
  const fallbackFormats = [
    "DD/MM/YYYY",
    "MM/DD/YYYY",
    "YYYY-MM-DD",
    "DD-MM-YYYY",
    "DD/MM/YYYY HH:mm:ss",
    "DD/MM/YYYY HH:mm"
  ];
  for (const fmt of fallbackFormats) {
    if (fmt === dayjsFmt) continue;
    const attempt = pureDayjs(str, fmt);
    if (attempt.isValid()) return attempt.toDate();
  }
  return null;
};
const applyTimeToDate = (date, time) => {
  const result = new Date(date);
  result.setHours(time.hours, time.minutes, time.seconds ?? 0, 0);
  return result;
};
const applyTimezone = (date) => {
  const dateStr = pureDayjs(date).format("YYYY-MM-DD HH:mm:ss");
  return dayjs(dateStr).toDate();
};
const toDayjs = (date) => dayjs(date);
const getDisplayFormat = (dateFormat, timeFormat, showTime) => {
  const fmt = showTime ? `${dateFormat} ${timeFormat}` : dateFormat;
  return normalizeToDateFnsFormat(fmt);
};
const isDatePartComplete = (part, maskEnabled, singleDateLen) => maskEnabled ? part.length >= singleDateLen : part.length > 0;
const parseRangeText = (text, displayFormat, maskEnabled, singleDateLen) => {
  const parts = text.split(" - ");
  if (parts.length !== 2) return null;
  if (!isDatePartComplete(parts[0], maskEnabled, singleDateLen) || !isDatePartComplete(parts[1], maskEnabled, singleDateLen))
    return null;
  const from = parseDate(parts[0], displayFormat);
  const to = parseDate(parts[1], displayFormat);
  return from && to ? [from, to] : null;
};

const TIMEZONE_OPTIONS = [
  { label: "Local", value: "" },
  { label: "UTC", value: "utc" }
];
const TimezoneSelect = ({
  value,
  onChange,
  className
}) => /* @__PURE__ */ jsxs("div", { className: cn("flex items-center gap-1.5 text-sm", className), children: [
  /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-xs", children: "Timezone" }),
  /* @__PURE__ */ jsx(
    "select",
    {
      value: value ?? "",
      onChange: (e) => onChange(e.target.value || void 0),
      className: cn(
        "rounded-md border border-input bg-background px-2 py-0.5 text-xs",
        "focus:outline-none focus:ring-1 focus:ring-ring"
      ),
      "aria-label": "Select timezone",
      children: TIMEZONE_OPTIONS.map((opt) => /* @__PURE__ */ jsx("option", { value: opt.value, children: opt.label }, opt.value))
    }
  )
] });
TimezoneSelect.displayName = "TimezoneSelect";

const DatePickerFooter = ({
  showTime,
  needConfirm,
  timezone,
  onTimezoneChange,
  onNow,
  onOk,
  className
}) => {
  const showOkButton = showTime || needConfirm;
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(
        "flex items-center border-t border-border px-3 py-2",
        className
      ),
      children: [
        /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: onNow, className: "text-xs", children: "Now" }),
        /* @__PURE__ */ jsx("div", { className: "flex-1" }),
        onTimezoneChange && /* @__PURE__ */ jsx(
          TimezoneSelect,
          {
            value: timezone,
            onChange: onTimezoneChange,
            className: "me-2"
          }
        ),
        showOkButton && /* @__PURE__ */ jsx(Button, { size: "sm", onClick: onOk, className: "text-xs", children: "OK" })
      ]
    }
  );
};
DatePickerFooter.displayName = "DatePickerFooter";

const DatePicker = forwardRef(
  ({
    value,
    defaultValue,
    onChange,
    type = "date",
    dateFormat = DEFAULT_DATE_FORMAT,
    timeFormat = DEFAULT_TIME_FORMAT,
    showTime = false,
    timePickerFormat = "24",
    showSeconds = false,
    minDate,
    maxDate,
    placeholder,
    label,
    error,
    helpText,
    size = "medium",
    disabled = false,
    allowClear = true,
    required = false,
    timezone,
    onTimezoneChange,
    onOk,
    needConfirm = false,
    onOpenChange,
    className,
    labelProps
  }, ref) => {
    const generatedId = useId();
    const errorId = `error_${generatedId}`;
    const helpTextId = `helpText_${generatedId}`;
    const containerRef = useRef(null);
    const inputRef = useRef(null);
    const cursorPosRef = useRef(null);
    const popoverContentId = useRef(
      `datepicker-popover-${generatedId}`
    ).current;
    const [open, setOpen] = useState(false);
    const [internalValue, setInternalValue] = useState(coerceDateValue(defaultValue, type) ?? null);
    const currentValue = value !== void 0 ? coerceDateValue(value, type) : internalValue;
    const [calendarMonth, setCalendarMonth] = useState(
      (type === "date" ? value ?? defaultValue : null) ?? /* @__PURE__ */ new Date()
    );
    const [rangeSelectionStep, setRangeSelectionStep] = useState(
      "from"
    );
    const [pendingDate, setPendingDate] = useState(null);
    const [pendingTime, setPendingTime] = useState({
      hours: 0,
      minutes: 0,
      seconds: 0
    });
    const displayFormat = getDisplayFormat(dateFormat, timeFormat, showTime);
    const sizeConfig = SIZE_CONFIG[size];
    const maskEnabled = isFixedWidthFormat(displayFormat);
    const maskTemplate = useMemo(
      () => maskEnabled ? type === "range" ? buildRangeMaskTemplate(displayFormat) : buildMaskTemplate(displayFormat) : null,
      [displayFormat, type, maskEnabled]
    );
    const singlePlaceholder = showTime ? `${dateFormat.toUpperCase()} ${timeFormat}` : dateFormat.toUpperCase();
    const defaultPlaceholder = type === "range" ? `${singlePlaceholder} - ${singlePlaceholder}` : singlePlaceholder;
    const getDisplayText = useCallback(() => {
      if (type === "range") {
        const rangeValue = currentValue;
        if (!rangeValue || !rangeValue[0] && !rangeValue[1]) return "";
        const from = rangeValue[0] ? formatDate(rangeValue[0], displayFormat) : "";
        const to = rangeValue[1] ? formatDate(rangeValue[1], displayFormat) : "";
        return `${from} - ${to}`;
      }
      return formatDate(currentValue, displayFormat);
    }, [currentValue, displayFormat, type]);
    const [inputText, setInputText] = useState(() => getDisplayText());
    useEffect(() => {
      if (!open) setInputText(getDisplayText());
    }, [getDisplayText, open]);
    const closePopover = useCallback(() => {
      setOpen(false);
      onOpenChange?.(false);
      setInputText(getDisplayText());
    }, [onOpenChange, getDisplayText]);
    const openPopover = useCallback(() => {
      setOpen(true);
      onOpenChange?.(true);
      setRangeSelectionStep("from");
      const dateVal = type === "date" ? currentValue : null;
      if (dateVal) {
        setCalendarMonth(dateVal);
        setPendingDate(dateVal);
        setPendingTime(dateToTimeValue(dateVal));
      } else {
        setPendingDate(null);
        setPendingTime({ hours: 0, minutes: 0, seconds: 0 });
      }
    }, [type, currentValue, onOpenChange]);
    useEffect(() => {
      if (!open) return;
      const handlePointerDown = (e) => {
        const target = e.target;
        if (containerRef.current?.contains(target)) return;
        const popoverEl = document.getElementById(popoverContentId);
        if (popoverEl?.contains(target)) return;
        closePopover();
      };
      document.addEventListener("pointerdown", handlePointerDown);
      return () => document.removeEventListener("pointerdown", handlePointerDown);
    }, [open, closePopover]);
    const commitValue = (date) => {
      if (date === null) {
        setInternalValue(null);
        onChange?.(null, "");
        setInputText("");
        return;
      }
      if (Array.isArray(date)) {
        setInternalValue(date);
        const converted2 = [
          applyTimezone(date[0]),
          applyTimezone(date[1])
        ];
        const formatted2 = [
          formatDate(date[0], displayFormat),
          formatDate(date[1], displayFormat)
        ];
        onChange?.([toDayjs(converted2[0]), toDayjs(converted2[1])], formatted2);
        setInputText(`${formatted2[0]} - ${formatted2[1]}`);
        return;
      }
      setInternalValue(date);
      const converted = applyTimezone(date);
      const formatted = formatDate(date, displayFormat);
      onChange?.(toDayjs(converted), formatted);
      setInputText(formatted);
    };
    const handleDateSelect = (selected) => {
      if (!selected) return;
      setCalendarMonth(selected);
      if (showTime || needConfirm) {
        setPendingDate(selected);
      } else {
        commitValue(selected);
        setOpen(false);
        onOpenChange?.(false);
      }
    };
    const handleRangeSelect = (range) => {
      if (!range) return;
      const from = range.from ?? null;
      const to = range.to ?? null;
      if (rangeSelectionStep === "from") {
        setInternalValue([from, null]);
        setRangeSelectionStep("to");
      } else {
        if (from && to) {
          if (showTime || needConfirm) {
            setPendingDate(from);
          } else {
            commitValue([from, to]);
            setOpen(false);
            onOpenChange?.(false);
          }
        } else if (from) {
          setInternalValue([from, null]);
        }
        setRangeSelectionStep("from");
      }
    };
    const handleTimeChange = (time) => {
      setPendingTime(time);
    };
    const handleNow = () => {
      const d = dayjs(/* @__PURE__ */ new Date());
      const now = new Date(
        d.year(),
        d.month(),
        d.date(),
        d.hour(),
        d.minute(),
        d.second()
      );
      if (showTime || needConfirm) {
        setPendingDate(now);
        setPendingTime(dateToTimeValue(now));
      } else {
        commitValue(now);
        setOpen(false);
        onOpenChange?.(false);
      }
    };
    const handleOk = () => {
      if (pendingDate) {
        const finalDate = showTime ? applyTimeToDate(pendingDate, pendingTime) : pendingDate;
        commitValue(finalDate);
        onOk?.(finalDate);
      }
      setOpen(false);
      onOpenChange?.(false);
    };
    const handleClear = (e) => {
      e.stopPropagation();
      e.preventDefault();
      commitValue(null);
    };
    useLayoutEffect(() => {
      if (cursorPosRef.current !== null && inputRef.current && document.activeElement === inputRef.current) {
        inputRef.current.setSelectionRange(
          cursorPosRef.current,
          cursorPosRef.current
        );
        cursorPosRef.current = null;
      }
    });
    const singleDateLen = useMemo(
      () => buildMaskTemplate(displayFormat).pattern.length,
      [displayFormat]
    );
    const parseAndApplyRange = (text) => {
      const parts = text.split(" - ");
      if (!isDatePartComplete(parts[0] ?? "", maskEnabled, singleDateLen))
        return;
      const from = parseDate(parts[0], displayFormat);
      if (from) setCalendarMonth(from);
      const range = parseRangeText(
        text,
        displayFormat,
        maskEnabled,
        singleDateLen
      );
      if (range) commitValue(range);
    };
    const handleInputChange = (e) => {
      let text = e.target.value;
      if (maskTemplate) {
        const masked = applyMask(
          text,
          maskTemplate,
          inputText,
          e.target.selectionStart
        );
        text = masked.text;
        cursorPosRef.current = masked.cursorPosition;
      }
      setInputText(text);
      if (type === "range") {
        parseAndApplyRange(text);
        return;
      }
      const isComplete = maskTemplate ? text.length >= maskTemplate.pattern.length : true;
      if (!isComplete) return;
      const parsed = parseDate(text, displayFormat);
      if (!parsed) return;
      setCalendarMonth(parsed);
      if (showTime || needConfirm) {
        setPendingDate(parsed);
        setPendingTime(dateToTimeValue(parsed));
      } else {
        commitValue(parsed);
      }
    };
    const handleInputKeyDown = (e) => {
      if (e.key === "Escape") return closePopover();
      if (e.key !== "Enter") return;
      if (type === "range") {
        const range = parseRangeText(
          inputText,
          displayFormat,
          maskEnabled,
          singleDateLen
        );
        if (range) commitValue(range);
      } else {
        const parsed = parseDate(inputText, displayFormat);
        if (parsed) commitValue(parsed);
      }
      setOpen(false);
      onOpenChange?.(false);
    };
    const handleInputFocus = () => {
      if (!open) openPopover();
    };
    const hasField = !!(label || error || helpText);
    const showFooter = showTime || needConfirm || !!onTimezoneChange;
    const todayDayjs = dayjs(/* @__PURE__ */ new Date());
    const todayDate = new Date(
      todayDayjs.year(),
      todayDayjs.month(),
      todayDayjs.date()
    );
    const ariaDescribedBy = [error ? errorId : null, helpText ? helpTextId : null].filter(Boolean).join(" ") || void 0;
    const calendarDisabled = useCallback(
      (date) => {
        if (minDate && date < new Date(minDate.setHours(0, 0, 0, 0)))
          return true;
        if (maxDate && date > new Date(maxDate.setHours(23, 59, 59, 999)))
          return true;
        return false;
      },
      [minDate, maxDate]
    );
    const calendarSelected = useCallback(() => {
      if (showTime || needConfirm) return pendingDate ?? void 0;
      return currentValue ?? void 0;
    }, [showTime, needConfirm, pendingDate, currentValue]);
    const triggerContent = /* @__PURE__ */ jsxs(Popover, { open, children: [
      /* @__PURE__ */ jsx(PopoverAnchor, { asChild: true, children: /* @__PURE__ */ jsxs(
        "div",
        {
          ref: containerRef,
          className: cn(
            "relative flex w-full items-center gap-2 rounded-md border border-input bg-background pe-8 ps-3",
            "focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",
            disabled && "cursor-not-allowed opacity-50",
            !!error && "border-destructive ring-destructive/20 ring-3",
            sizeConfig.trigger,
            !hasField && className
          ),
          children: [
            /* @__PURE__ */ jsx(
              Calendar,
              {
                className: cn("shrink-0 text-muted-foreground", sizeConfig.icon)
              }
            ),
            /* @__PURE__ */ jsx(
              "input",
              {
                ref: inputRef,
                type: "text",
                disabled,
                "aria-label": label || "Pick a date",
                "aria-describedby": ariaDescribedBy,
                "aria-invalid": !!error || void 0,
                placeholder: placeholder ?? defaultPlaceholder,
                value: inputText,
                onChange: handleInputChange,
                onKeyDown: handleInputKeyDown,
                onFocus: handleInputFocus,
                className: cn(
                  "min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground",
                  "disabled:cursor-not-allowed",
                  sizeConfig.trigger.split(" ").find((c) => c.startsWith("text-"))
                )
              }
            ),
            timezone && /* @__PURE__ */ jsx("span", { className: "shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground", children: timezone.toUpperCase() }),
            allowClear && /* @__PURE__ */ jsx(
              "button",
              {
                type: "button",
                onPointerDown: (e) => e.preventDefault(),
                onClick: handleClear,
                className: cn(
                  "absolute inset-y-0 end-2 flex items-center text-muted-foreground hover:text-foreground focus:outline-none",
                  !(inputText && !disabled) && "invisible"
                ),
                "aria-label": "Clear date",
                tabIndex: -1,
                children: /* @__PURE__ */ jsx(X, { className: sizeConfig.icon })
              }
            )
          ]
        }
      ) }),
      open && /* @__PURE__ */ jsxs(
        PopoverContent,
        {
          id: popoverContentId,
          className: "w-auto p-0",
          align: "start",
          onOpenAutoFocus: (e) => e.preventDefault(),
          onCloseAutoFocus: (e) => e.preventDefault(),
          onPointerDownOutside: (e) => e.preventDefault(),
          onInteractOutside: (e) => e.preventDefault(),
          children: [
            /* @__PURE__ */ jsxs("div", { className: cn("flex", showTime && "flex-row"), children: [
              type === "date" ? /* @__PURE__ */ jsx(
                Calendar$1,
                {
                  mode: "single",
                  captionLayout: "dropdown",
                  today: todayDate,
                  month: calendarMonth,
                  onMonthChange: setCalendarMonth,
                  selected: calendarSelected(),
                  onSelect: handleDateSelect,
                  disabled: calendarDisabled,
                  ...minDate && { fromDate: minDate },
                  ...maxDate && { toDate: maxDate }
                }
              ) : /* @__PURE__ */ jsx(
                Calendar$1,
                {
                  mode: "range",
                  numberOfMonths: 2,
                  captionLayout: "dropdown",
                  today: todayDate,
                  className: "[&_[data-outside][data-selected=true]]:!bg-transparent [&_[data-outside][data-selected=true]]:after:!bg-transparent [&_[data-outside]_button]:!bg-transparent [&_[data-outside]_button]:!text-muted-foreground",
                  month: calendarMonth,
                  onMonthChange: setCalendarMonth,
                  selected: currentValue ? {
                    from: currentValue[0] ?? void 0,
                    to: currentValue[1] ?? void 0
                  } : void 0,
                  onSelect: handleRangeSelect,
                  disabled: calendarDisabled,
                  ...minDate && { fromDate: minDate },
                  ...maxDate && { toDate: maxDate }
                }
              ),
              showTime && /* @__PURE__ */ jsx("div", { className: "border-inline-start border-border", children: /* @__PURE__ */ jsx(
                TimePickerPanel,
                {
                  value: pendingTime,
                  onChange: handleTimeChange,
                  format: timePickerFormat,
                  showSeconds,
                  disabled
                }
              ) })
            ] }),
            showFooter && /* @__PURE__ */ jsx(
              DatePickerFooter,
              {
                showTime,
                needConfirm,
                timezone,
                onTimezoneChange,
                onNow: handleNow,
                onOk: handleOk
              }
            )
          ]
        }
      )
    ] });
    if (!hasField) {
      return /* @__PURE__ */ jsx("div", { ref, className, children: triggerContent });
    }
    return /* @__PURE__ */ jsxs(
      Field,
      {
        ref,
        "data-disabled": disabled || void 0,
        "data-invalid": !!error || void 0,
        className,
        children: [
          label && /* @__PURE__ */ jsxs(
            FieldLabel,
            {
              ...labelProps,
              children: [
                label,
                required && /* @__PURE__ */ jsx("span", { "aria-hidden": "true", className: "text-destructive", children: "*" })
              ]
            }
          ),
          /* @__PURE__ */ jsxs(FieldContent, { children: [
            triggerContent,
            !!error && /* @__PURE__ */ jsx(FieldError, { id: errorId, children: error }),
            helpText && /* @__PURE__ */ jsx(FieldDescription, { id: helpTextId, children: helpText })
          ] })
        ]
      }
    );
  }
);
DatePicker.displayName = "DatePicker";

export { DatePicker as D };
//# sourceMappingURL=DatePicker-snpsZuUL.js.map
