import { jsxs, jsx } from "react/jsx-runtime";
import { forwardRef, useRef, useState, useEffect, useCallback, useMemo } from "react";
import moment from "moment";
import "../../node_modules/react-dates/lib/initialize.js";
import { DatePickerDropdown } from "./datePickerDropdown.js";
import { DatePickerInput } from "./datePickerInput.js";
/* empty css                                                     */
/* empty css                       */
const DatePicker = forwardRef(
  ({
    fullWidth,
    label,
    isRequired,
    labelOrientation = "top",
    isError,
    isDisabled,
    closeOnDateSelect,
    placeholder,
    selectedDate,
    setSelectedDate,
    handleDateChange,
    showWeekNumbers,
    primaryButtonProps,
    secondaryButtonProps,
    tertiaryButtonProps,
    onPrimaryButtonClick,
    onSecondaryButtonClick,
    onTertiaryButtonClick,
    withPortal,
    portalContainer = typeof document !== "undefined" ? document.body : void 0,
    showMonthYearSelect,
    customYears,
    displayFormat = "DD-MM-YYYY",
    minDate,
    maxDate,
    onClickOutside,
    isOutsideRange,
    isAgGridCellRenderer = false,
    customIcon,
    readOnly,
    inputProps,
    className,
    ...args
  }, ref) => {
    const dateString = selectedDate && moment.isMoment(selectedDate) && selectedDate.isValid() ? selectedDate.format(displayFormat) : "";
    const datePickerMainContainerRef = useRef(null);
    const inputContainerRef = useRef(null);
    const [isOpen, setIsOpen] = useState(false);
    const [focused, setFocused] = useState(false);
    const [inputValue, setInputValue] = useState(dateString || "");
    const [cancelTrigger, setCancelTrigger] = useState(0);
    useEffect(() => {
      setInputValue(dateString || "");
    }, [dateString]);
    const handleDateStringChange = (value) => {
      if (value === null) {
        setSelectedDate == null ? void 0 : setSelectedDate(null);
        setInputValue("");
        return;
      }
      if (moment.isMoment(value)) {
        if (minDate && value.isBefore(minDate, "day")) {
          setInputValue(value.format(displayFormat));
          setSelectedDate == null ? void 0 : setSelectedDate(null);
          return;
        }
        if (maxDate && value.isAfter(maxDate, "day")) {
          setInputValue(value.format(displayFormat));
          setSelectedDate == null ? void 0 : setSelectedDate(null);
          return;
        }
        setSelectedDate == null ? void 0 : setSelectedDate(value);
        setInputValue(value.format(displayFormat));
      } else {
        const parsedDate = moment(value, displayFormat, true);
        if (parsedDate.isValid()) {
          if (minDate != null && parsedDate.isBefore(minDate, "day")) {
            setInputValue(value);
            setSelectedDate == null ? void 0 : setSelectedDate(null);
            return;
          }
          if (maxDate != null && parsedDate.isAfter(maxDate, "day")) {
            setInputValue(value);
            setSelectedDate == null ? void 0 : setSelectedDate(null);
            return;
          }
          setSelectedDate == null ? void 0 : setSelectedDate(parsedDate);
        }
        setInputValue(value);
      }
    };
    const handleClear = () => {
      setSelectedDate == null ? void 0 : setSelectedDate(null);
      setInputValue("");
      setCancelTrigger((prev) => prev + 1);
      onTertiaryButtonClick == null ? void 0 : onTertiaryButtonClick();
      setFocused(false);
      setTimeout(() => {
        setFocused(true);
      }, 0);
    };
    const handleCancel = () => {
      setSelectedDate == null ? void 0 : setSelectedDate(null);
      setInputValue("");
      setIsOpen(false);
      onSecondaryButtonClick == null ? void 0 : onSecondaryButtonClick();
    };
    const handleClickOutside = useCallback(
      (event) => {
        var _a;
        const target = event.target;
        const el = target;
        const isWithinMainContainer = (_a = datePickerMainContainerRef.current) == null ? void 0 : _a.contains(target);
        const isWithinPortalContainer = withPortal && el.closest(".impact-portal-container");
        const isWithinButtonsContainer = el.closest(".datePicker-buttons-container");
        if (!isWithinMainContainer && !isWithinPortalContainer && !isWithinButtonsContainer && !isAgGridCellRenderer && !el.closest(".ia-select-container-v3-styled-menu ") && isOpen) {
          onClickOutside == null ? void 0 : onClickOutside();
          setIsOpen(false);
        }
      },
      [isOpen, isAgGridCellRenderer, withPortal, onClickOutside]
    );
    useEffect(() => {
      setFocused(isOpen);
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }, [isOpen, handleClickOutside]);
    const onDatesChange = (date) => {
      if (handleDateChange) {
        handleDateChange(date);
      } else {
        setSelectedDate == null ? void 0 : setSelectedDate(date);
      }
      if (closeOnDateSelect) {
        setIsOpen(false);
      }
    };
    const computedIsError = useMemo(
      () => Boolean(isError ?? (selectedDate != null && (isOutsideRange == null ? void 0 : isOutsideRange(selectedDate)))),
      [isError, selectedDate, isOutsideRange]
    );
    const normalizedCustomYears = useMemo(() => {
      if (!customYears || customYears.length === 0) return void 0;
      const first = customYears[0];
      if (first !== null && typeof first === "object" && "label" in first) {
        return customYears;
      }
      return customYears.map((y) => ({ label: String(y), value: String(y) }));
    }, [customYears]);
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: `impact-datepicker-main-container ${labelOrientation === "left" ? "label-flex-row" : "label-flex-column"} ${fullWidth === true ? "impact-datepicker-full-width-main-container" : ""} ${className ?? ""}`.trim(),
        children: [
          label && /* @__PURE__ */ jsxs("div", { className: "datePicker-label", children: [
            label,
            " ",
            isRequired && /* @__PURE__ */ jsx("span", { style: { color: "red" }, children: "*" })
          ] }),
          /* @__PURE__ */ jsxs("div", { ref: datePickerMainContainerRef, className: "datePicker-container", children: [
            /* @__PURE__ */ jsx(
              DatePickerInput,
              {
                customIcon,
                dateString: inputValue,
                displayFormat,
                inputContainerRef,
                inputProps,
                isDisabled,
                isError: computedIsError,
                isOpen,
                maxDate: maxDate ?? null,
                minDate: minDate ?? null,
                placeholder,
                readOnly,
                selectedDate: selectedDate ?? null,
                setIsOpen,
                onCancel: cancelTrigger,
                onDateStringChange: handleDateStringChange,
                ...args
              }
            ),
            isOpen && /* @__PURE__ */ jsx(
              DatePickerDropdown,
              {
                containerRef: datePickerMainContainerRef,
                customYears: normalizedCustomYears,
                focused,
                isOutsideRange,
                maxDate: maxDate ?? null,
                minDate: minDate ?? null,
                portalContainer,
                primaryButtonProps,
                secondaryButtonProps,
                selectedDate: selectedDate ?? null,
                setFocused,
                setIsOpen,
                setSelectedDate,
                showMonthYearSelect,
                showWeekNumbers,
                tertiaryButtonProps,
                withPortal,
                onDatesChange,
                onPrimaryButtonClick,
                onSecondaryButtonClick: handleCancel,
                onTertiaryButtonClick: handleClear
              }
            )
          ] })
        ]
      }
    );
  }
);
DatePicker.displayName = "DatePicker";
export {
  DatePicker
};
