import { jsxs, jsx } from "react/jsx-runtime";
import { forwardRef, useRef, useState, useCallback, useEffect } from "react";
import moment from "moment";
import "../../node_modules/react-dates/lib/initialize.js";
import { DateRangePickerDropdown } from "./dateRangePickerDropdown.js";
import { DateRangePickerInput } from "./dateRangePickerInput.js";
import { rangeSelectorTypes } from "./utils.js";
import { HelperText } from "../common/HelperText/index.js";
/* empty css                                                     */
/* empty css                            */
const DateRangePicker = forwardRef(
  ({
    label,
    isRequired,
    labelOrientation = "top",
    fullWidth,
    startDate,
    setStartDate,
    startDateInputProps,
    endDate,
    setEndDate,
    endDateInputProps,
    isDisabled,
    isError,
    withPortal,
    handleDatesChange,
    handleFocusChange,
    portalContainer = typeof document !== "undefined" ? document.body : void 0,
    showWeekNumbers,
    tertiaryButtonProps,
    primaryButtonProps,
    onPrimaryButtonClick,
    onSecondaryButtonClick,
    onResetClick,
    showRangeSelector,
    showMonthYearSelect,
    customYears,
    handleStartDateFocus,
    handleEndDateFocus,
    displayFormat = "DD-MM-YYYY",
    customWeekNumberData,
    suppressClickOnWeekNumber = false,
    isAgGridCellRenderer = false,
    minDate,
    maxDate,
    readOnly = false,
    startDateOffset,
    endDateOffset,
    helperText,
    isOutsideRange,
    portalClassName,
    customIcon,
    className
  }, ref) => {
    const dateRangePickerMainContainerRef = useRef(null);
    const inputContainerRef = useRef(null);
    const dropDownContainerRef = useRef(null);
    const startDateInputRef = useRef(null);
    const endDateInputRef = useRef(null);
    const startDateString = (startDate == null ? void 0 : startDate.format(displayFormat)) ?? "";
    const endDateString = (endDate == null ? void 0 : endDate.format(displayFormat)) ?? "";
    const selectedDaysNumber = startDate != null && endDate != null ? endDate.diff(startDate, "days") + 1 : 0;
    const [isOpen, setIsOpen] = useState(false);
    const [focusedInput, setFocusedInput] = useState("startDate");
    const [tempStartDate, setTempStartDate] = useState(startDate ?? null);
    const [tempEndDate, setTempEndDate] = useState(endDate ?? null);
    const [selectedRange, setSelectedRange] = useState(rangeSelectorTypes[0].id);
    const [hasInputErrors, setHasInputErrors] = useState(false);
    const [clearErrorsTrigger, setClearErrorsTrigger] = useState(0);
    const [resetTrigger, setResetTrigger] = useState(0);
    const resetClicked = useRef(false);
    const onStartDateFocus = useCallback(() => {
      if (handleStartDateFocus) {
        handleStartDateFocus(setFocusedInput);
      }
      setFocusedInput("startDate");
      setIsOpen(true);
    }, [handleStartDateFocus]);
    const onEndDateFocus = useCallback(() => {
      if (handleEndDateFocus) {
        handleEndDateFocus(setFocusedInput);
      }
      setFocusedInput("endDate");
      setIsOpen(true);
    }, [handleEndDateFocus]);
    const onDatesChange = useCallback(
      ({ startDate: sd, endDate: ed }) => {
        if (handleDatesChange) {
          handleDatesChange(sd, ed);
        } else {
          setStartDate == null ? void 0 : setStartDate(sd);
          setEndDate == null ? void 0 : setEndDate(ed);
        }
        setClearErrorsTrigger((prev) => prev + 1);
      },
      [handleDatesChange, setStartDate, setEndDate]
    );
    const onFocusChange = useCallback(
      (focused) => {
        if (handleFocusChange) {
          handleFocusChange(focused, setFocusedInput, startDateInputRef, endDateInputRef);
          return;
        }
        setFocusedInput(focused ?? "startDate");
        setTimeout(() => {
          var _a, _b, _c, _d;
          if (focused === null || focused === "startDate") {
            (_a = startDateInputRef.current) == null ? void 0 : _a.focus();
            (_b = startDateInputRef.current) == null ? void 0 : _b.setSelectionRange(0, 0);
          }
          if (focused === "endDate") {
            (_c = endDateInputRef.current) == null ? void 0 : _c.focus();
            (_d = endDateInputRef.current) == null ? void 0 : _d.setSelectionRange(0, 0);
          }
        }, 0);
      },
      [handleFocusChange]
    );
    const handleRangeSelectorChange = useCallback((event) => {
      setSelectedRange(event.target.value);
      setFocusedInput("startDate");
    }, []);
    const handleClickOutside = useCallback(
      (event) => {
        const target = event.target;
        if (inputContainerRef.current != null && !inputContainerRef.current.contains(target) && dropDownContainerRef.current != null && !dropDownContainerRef.current.contains(target) && !target.closest(".ia-select-container-v3-styled-menu ") && !isAgGridCellRenderer && isOpen) {
          setIsOpen(false);
          if (!resetClicked.current) {
            setStartDate == null ? void 0 : setStartDate(tempStartDate);
            setEndDate == null ? void 0 : setEndDate(tempEndDate);
            setClearErrorsTrigger((prev) => prev + 1);
          }
          resetClicked.current = false;
        }
      },
      [isOpen, isAgGridCellRenderer, tempStartDate, tempEndDate, setStartDate, setEndDate]
    );
    useEffect(() => {
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }, [handleClickOutside]);
    const handleResetDates = useCallback(() => {
      resetClicked.current = true;
      setHasInputErrors(false);
      setClearErrorsTrigger((prev) => prev + 1);
      setResetTrigger((prev) => prev + 1);
      if (onResetClick) {
        onResetClick();
      } else {
        setStartDate == null ? void 0 : setStartDate(null);
        setEndDate == null ? void 0 : setEndDate(null);
        setTempEndDate(null);
        setTempStartDate(null);
        setFocusedInput("startDate");
      }
    }, [onResetClick, setStartDate, setEndDate]);
    const handleCancelDates = useCallback(() => {
      onSecondaryButtonClick == null ? void 0 : onSecondaryButtonClick();
      setStartDate == null ? void 0 : setStartDate(tempStartDate);
      setEndDate == null ? void 0 : setEndDate(tempEndDate);
      setFocusedInput("startDate");
      setIsOpen(false);
    }, [onSecondaryButtonClick, tempStartDate, tempEndDate, setStartDate, setEndDate]);
    const handleApplyDates = useCallback(() => {
      if (hasInputErrors) return;
      onPrimaryButtonClick == null ? void 0 : onPrimaryButtonClick();
      setIsOpen(false);
      setTempStartDate(startDate ?? null);
      setTempEndDate(endDate ?? null);
    }, [hasInputErrors, onPrimaryButtonClick, startDate, endDate]);
    const handleStartDateStringChange = useCallback(
      (value) => {
        if (value === null) {
          setStartDate == null ? void 0 : setStartDate(null);
          return;
        }
        if (moment.isMoment(value)) {
          if (minDate != null && value.isBefore(minDate, "day")) return;
          if (maxDate != null && value.isAfter(maxDate, "day")) return;
          if (endDate != null && value.isAfter(endDate, "day")) return;
          setStartDate == null ? void 0 : setStartDate(value);
        } else {
          const parsed = moment(value, displayFormat, true);
          if (parsed.isValid()) {
            if (minDate != null && parsed.isBefore(minDate, "day")) return;
            if (maxDate != null && parsed.isAfter(maxDate, "day")) return;
            if (endDate != null && parsed.isAfter(endDate, "day")) return;
            setStartDate == null ? void 0 : setStartDate(parsed);
          }
        }
      },
      [displayFormat, minDate, maxDate, endDate, setStartDate]
    );
    const handleEndDateStringChange = useCallback(
      (value) => {
        if (value === null) {
          setEndDate == null ? void 0 : setEndDate(null);
          return;
        }
        if (moment.isMoment(value)) {
          if (minDate != null && value.isBefore(minDate, "day")) return;
          if (maxDate != null && value.isAfter(maxDate, "day")) return;
          if (startDate != null && value.isBefore(startDate, "day")) return;
          setEndDate == null ? void 0 : setEndDate(value);
        } else {
          const parsed = moment(value, displayFormat, true);
          if (parsed.isValid()) {
            if (minDate != null && parsed.isBefore(minDate, "day")) return;
            if (maxDate != null && parsed.isAfter(maxDate, "day")) return;
            if (startDate != null && parsed.isBefore(startDate, "day")) return;
            setEndDate == null ? void 0 : setEndDate(parsed);
          }
        }
      },
      [displayFormat, minDate, maxDate, startDate, setEndDate]
    );
    const normalizedCustomYears = customYears == null || customYears.length === 0 ? void 0 : typeof customYears[0] === "object" && customYears[0] !== null ? customYears : customYears.map((y) => ({ label: String(y), value: String(y) }));
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: `impact-dateRangePicker-main-container ${labelOrientation === "left" ? "label-flex-row" : "label-flex-column"} ${fullWidth === true ? "impact-dateRangePicker-full-width-main-container" : ""} ${className ?? ""}`.trim(),
        children: [
          label != null && /* @__PURE__ */ jsxs("div", { className: "dateRangePicker-label", children: [
            label,
            " ",
            isRequired === true && /* @__PURE__ */ jsx("span", { style: { color: "red" }, children: "*" })
          ] }),
          /* @__PURE__ */ jsxs("div", { ref: dateRangePickerMainContainerRef, className: "dateRangePicker-container", children: [
            /* @__PURE__ */ jsx(
              DateRangePickerInput,
              {
                clearErrorsTrigger,
                customIcon,
                displayFormat,
                endDateInputProps,
                endDateInputRef,
                endDateString,
                inputContainerRef,
                isDisabled,
                isError,
                isOutsideRange,
                maxDate: maxDate ?? null,
                minDate: minDate ?? null,
                readOnly,
                resetTrigger,
                startDateInputProps,
                startDateInputRef,
                startDateString,
                onEndDateFocus,
                onEndDateStringChange: handleEndDateStringChange,
                onErrorStateChange: setHasInputErrors,
                onStartDateFocus,
                onStartDateStringChange: handleStartDateStringChange
              }
            ),
            isOpen && /* @__PURE__ */ jsx(
              DateRangePickerDropdown,
              {
                containerRef: dateRangePickerMainContainerRef,
                customWeekNumberData,
                customYears: normalizedCustomYears,
                dropDownContainerRef,
                endDate: endDate ?? null,
                endDateOffset,
                focusedInput,
                handleApplyDates,
                handleCancelDates,
                handleRangeSelectorChange,
                handleResetDates,
                hasInputErrors,
                portalClassName,
                portalContainer,
                primaryButtonProps,
                selectedDaysNumber,
                selectedRange,
                setIsOpen,
                showMonthYearSelect,
                showRangeSelector,
                showWeekNumbers,
                startDate: startDate ?? null,
                startDateOffset,
                suppressClickOnWeekNumber,
                tertiaryButtonProps,
                withPortal,
                onDatesChange,
                onFocusChange,
                onSecondaryButtonClick
              }
            )
          ] }),
          helperText != null && helperText !== "" && /* @__PURE__ */ jsx(HelperText, { error: isError, helper: isError === true ? helperText : "" })
        ]
      }
    );
  }
);
DateRangePicker.displayName = "DateRangePicker";
export {
  DateRangePicker
};
