import { Box, NumberInput, Popover, Slider } from "@wix/design-system";
import React, { useRef, useState } from "react";
import { usePopoverAppendToElement } from "./../ui-components-provider.js";
import classes from "./input-with-slider-scss.js";
const SLIDER_WIDTH = 88;
const SLIDER_GAP = 18;
const SLIDER_PADDING = 12;
const InputWithSlider = ({
  value,
  onChange,
  onChangeCommit,
  commitUnchanged = false,
  gradientColor,
  zIndex,
  prefix,
  suffix,
  min,
  max,
  dataHook
}) => {
  const [isFocused, setIsFocused] = React.useState(false);
  const inputRef = useRef(null);
  const inputWrapperRef = React.useRef(null);
  const [inputValue, setInputValue] = useState(value ?? "");
  const [sliderValue, setSliderValue] = useState(value ?? min);
  const [inputKey, setInputKey] = useState(0);
  const sliderValueRef = useRef(value ?? min);
  const originalValueRef = useRef(value ?? min);
  const isDraggingRef = useRef(false);
  const commitTimeoutRef = useRef(void 0);
  const removeDragEndListenersRef = useRef(void 0);
  const appendToElement = usePopoverAppendToElement();
  const inputWrapperDimensions = inputWrapperRef.current?.getBoundingClientRect() ?? { width: 0 };
  const popoverZIndex = `calc(${zIndex} + 100)`;
  const numberInputZIndex = `calc(${popoverZIndex} + 1)`;
  React.useEffect(() => {
    const newValue = value ?? "";
    if (newValue !== inputValue) {
      setInputValue(newValue);
    }
    if (!isDraggingRef.current && typeof value === "number") {
      setSliderValue(value);
      sliderValueRef.current = value;
    }
  }, [value]);
  React.useEffect(
    () => () => {
      removeDragEndListenersRef.current?.();
      if (commitTimeoutRef.current !== void 0) {
        window.clearTimeout(commitTimeoutRef.current);
      }
    },
    []
  );
  const handleInputWithinBounds = (data, shouldCommit = true) => {
    const numberValue = Math.round(Number(data));
    const valueWithinBounds = isNaN(numberValue) || numberValue < min ? min : numberValue > max ? max : numberValue;
    setInputValue(valueWithinBounds);
    setSliderValue(valueWithinBounds);
    sliderValueRef.current = valueWithinBounds;
    if (value !== valueWithinBounds || commitUnchanged) {
      onChange(valueWithinBounds);
      if (shouldCommit) {
        onChangeCommit?.(valueWithinBounds, originalValueRef.current);
        originalValueRef.current = valueWithinBounds;
      }
      return;
    }
    setInputKey((prev) => prev + 1);
  };
  const commitSliderValue = () => {
    if (!isDraggingRef.current) {
      return;
    }
    isDraggingRef.current = false;
    const finalValue = sliderValueRef.current;
    const originalValue = originalValueRef.current;
    if (finalValue !== originalValue || commitUnchanged) {
      onChangeCommit?.(finalValue, originalValue);
    }
    originalValueRef.current = finalValue;
  };
  const scheduleSliderCommit = () => {
    if (commitTimeoutRef.current !== void 0) {
      window.clearTimeout(commitTimeoutRef.current);
    }
    commitTimeoutRef.current = window.setTimeout(() => {
      commitTimeoutRef.current = void 0;
      commitSliderValue();
    });
  };
  const handleSliderDragStart = (event) => {
    removeDragEndListenersRef.current?.();
    isDraggingRef.current = true;
    originalValueRef.current = value ?? min;
    sliderValueRef.current = sliderValue;
    const ownerDocument = event.currentTarget.ownerDocument;
    const handleDocumentPointerUp = () => {
      removeDragEndListenersRef.current?.();
      scheduleSliderCommit();
    };
    removeDragEndListenersRef.current = () => {
      ownerDocument.removeEventListener("pointerup", handleDocumentPointerUp, true);
      ownerDocument.removeEventListener("pointercancel", handleDocumentPointerUp, true);
      removeDragEndListenersRef.current = void 0;
    };
    ownerDocument.addEventListener("pointerup", handleDocumentPointerUp, true);
    ownerDocument.addEventListener("pointercancel", handleDocumentPointerUp, true);
  };
  const handleSliderChange = (sliderValue2) => {
    const newValue = typeof sliderValue2 === "number" ? sliderValue2 : sliderValue2[0];
    sliderValueRef.current = newValue;
    setSliderValue(newValue);
    setInputValue(newValue);
    onChange(newValue);
  };
  return /* @__PURE__ */ React.createElement(
    Popover,
    {
      shown: isFocused,
      placement: "right",
      moveBy: { x: -inputWrapperDimensions.width - SLIDER_WIDTH - SLIDER_GAP - SLIDER_PADDING - 6 },
      zIndex: popoverZIndex,
      onClickOutside: () => setIsFocused(false),
      fixed: true,
      appendTo: appendToElement
    },
    /* @__PURE__ */ React.createElement(Popover.Element, null, /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: inputWrapperRef,
        style: isFocused ? { position: "relative", zIndex: numberInputZIndex } : void 0
      },
      /* @__PURE__ */ React.createElement(
        NumberInput,
        {
          inputRef,
          key: inputKey,
          size: "small",
          prefix,
          suffix,
          value: inputValue,
          min,
          max,
          onFocus: () => {
            setIsFocused(true);
          },
          onChange: (value2, stringValue) => {
            if (stringValue === "") {
              setInputValue("");
              return;
            }
            if (typeof value2 === "number") {
              onChange(value2);
              setInputValue(value2);
            }
          },
          onBlur: (e) => handleInputWithinBounds(e.target.value, true),
          onKeyDown: (e) => {
            if (["Enter", "Escape"].includes(e.key)) {
              handleInputWithinBounds(inputRef.current?.value, true);
            }
          },
          hideStepper: true,
          dataHook
        }
      )
    )),
    /* @__PURE__ */ React.createElement(Popover.Content, null, /* @__PURE__ */ React.createElement("div", { className: classes.sliderContainer }, /* @__PURE__ */ React.createElement("div", { style: { width: SLIDER_WIDTH }, onPointerDown: handleSliderDragStart }, /* @__PURE__ */ React.createElement(
      Slider,
      {
        gradientColor,
        displayMarks: false,
        min,
        max,
        value: sliderValue,
        onChange: handleSliderChange,
        displayTooltip: false
      }
    )), /* @__PURE__ */ React.createElement(Box, { width: inputWrapperDimensions.width })))
  );
};
export {
  InputWithSlider
};
//# sourceMappingURL=input-with-slider.js.map
