"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const ahooks = require("ahooks");
const lodashEs = require("lodash-es");
const React = require("react");
;/* empty css                                                                                                                                                                                        */
;/* empty css                                                                                                                                                                                         */
;/* empty css                                                                                                                                                                                                 */
;/* empty css                                                                                                                                                                                            */
;/* empty css                                                                                                                                                                                            */
const dayjs = require("../../utils/dayjs.cjs");
const constant = require("./constant.cjs");
const Flex = require("../../node_modules/.pnpm/@mantine_core@7.17.8_patch_hash_3qirwkgu3wxhvd6hnr2gb24yzq_@mantine_hooks@7.17.8_react@18.3.1_e5yvlgwhmeykc75dkphi7jou6q/node_modules/@mantine/core/esm/components/Flex/Flex.cjs");
const useUncontrolled = require("../../node_modules/.pnpm/@mantine_hooks@7.17.8_react@18.3.1/node_modules/@mantine/hooks/esm/use-uncontrolled/use-uncontrolled.cjs");
const ScrollArea = require("../../node_modules/.pnpm/@mantine_core@7.17.8_patch_hash_3qirwkgu3wxhvd6hnr2gb24yzq_@mantine_hooks@7.17.8_react@18.3.1_e5yvlgwhmeykc75dkphi7jou6q/node_modules/@mantine/core/esm/components/ScrollArea/ScrollArea.cjs");
const Box = require("../../node_modules/.pnpm/@mantine_core@7.17.8_patch_hash_3qirwkgu3wxhvd6hnr2gb24yzq_@mantine_hooks@7.17.8_react@18.3.1_e5yvlgwhmeykc75dkphi7jou6q/node_modules/@mantine/core/esm/core/Box/Box.cjs");
const createStyles = require("../../node_modules/.pnpm/@mantine_emotion@7.17.8_patch_hash_op2x5ib3e7mgdsoy22n5xoaf4q_@emotion_cache@11.14.0_@emotion_54ygowx4natmcqkxvanlwrr74u/node_modules/@mantine/emotion/esm/create-styles.cjs");
const useStyles = createStyles.createStyles((theme) => ({
  bold: {
    fontWeight: 600
  },
  cell: {
    textAlign: "center",
    cursor: "pointer",
    scrollSnapAlign: "start",
    userSelect: "none"
  },
  cellDisabled: {
    textAlign: "center",
    scrollSnapAlign: "start",
    userSelect: "none",
    cursor: "not-allowed",
    color: theme.colors.carbon[6],
    opacity: 0.5
  },
  cellPlaceholder: {
    visibility: "hidden"
  }
}));
const getTimeRange = ({
  curr,
  type,
  start,
  end
}) => {
  const map = {
    year: {
      min: dayjs.dayjs().year(),
      max: dayjs.dayjs().year() + 100
    },
    month: {
      min: 1,
      max: 12
    },
    day: {
      min: 1,
      max: curr.daysInMonth()
    },
    hour: {
      min: 0,
      max: 23
    },
    minute: {
      min: 0,
      max: 59
    },
    second: {
      min: 0,
      max: 59
    }
  };
  let { min, max } = map[type];
  const s1 = start ? dayjs.dayjs(start) : null;
  const s2 = end ? dayjs.dayjs(end) : null;
  switch (type) {
    case "year": {
      if (s1) {
        min = s1.year();
      }
      if (s2) {
        max = s2.year();
      }
      break;
    }
    case "month": {
      if (s1 && curr.isSame(s1, "year")) {
        min = s1.month() + 1;
      }
      if (s2 && curr.isSame(s2, "year")) {
        max = s2.month() + 1;
      }
      break;
    }
    case "day": {
      if (s1 && curr.isSame(s1, "month")) {
        min = s1.date();
      }
      if (s2 && curr.isSame(s2, "month")) {
        max = s2.date();
      }
      break;
    }
    case "hour": {
      if (s1 && curr.isSame(s1, "day")) {
        min = s1.hour();
      }
      if (s2 && curr.isSame(s2, "day")) {
        max = s2.hour();
      }
      break;
    }
    case "minute": {
      if (s1 && curr.isSame(s1, "hour")) {
        min = s1.minute();
      }
      if (s2 && curr.isSame(s2, "hour")) {
        max = s2.minute();
      }
      break;
    }
    case "second": {
      if (s1 && curr.isSame(s1, "minute")) {
        min = s1.second();
      }
      if (s2 && curr.isSame(s2, "minute")) {
        max = s2.second();
      }
      break;
    }
    default: {
      const exhaustiveCheck = "should not reach here";
      throw new Error(exhaustiveCheck);
    }
  }
  return { min, max };
};
const default2DigitRender = (val) => lodashEs.padStart(String(val), 2, "0");
function TimePickerScrollerColumn({
  min,
  max,
  curr,
  render = default2DigitRender,
  onChange,
  name,
  currentValueChangedBy
}) {
  const { classes, cx: clsx } = useStyles();
  const ref = React.useRef(null);
  const fullRange = React.useMemo(() => {
    switch (name) {
      case "hour":
        return lodashEs.range(0, 24);
      case "minute":
      case "second":
        return lodashEs.range(0, 60);
      default:
        return lodashEs.range(min, max + 1);
    }
  }, [name, min, max]);
  const numbers = fullRange;
  const timeoutRef = React.useRef();
  const isArtificialScroll = React.useRef(false);
  const isDisabled = React.useMemo(() => (val2) => val2 < min || val2 > max, [min, max]);
  const [val, setVal] = useUncontrolled.useUncontrolled({
    value: curr,
    onChange
  });
  const adjustScrollTop = ahooks.useMemoizedFn((value) => {
    if (currentValueChangedBy === "timeScroller") return;
    const i = numbers.findIndex((i2) => i2 === value);
    if (i !== -1 && ref.current) {
      isArtificialScroll.current = true;
      ref.current.scrollTop = i * constant.CellHeight;
      window.requestAnimationFrame(() => {
        setTimeout(() => {
          isArtificialScroll.current = false;
        }, 100);
      });
    }
  });
  const findNearestValidValue = ahooks.useMemoizedFn((targetIndex) => {
    let upIndex = targetIndex;
    let downIndex = targetIndex;
    while (upIndex >= 0 || downIndex < numbers.length) {
      if (upIndex >= 0 && upIndex < numbers.length) {
        const upVal = numbers[upIndex];
        if (!isDisabled(upVal)) {
          return { value: upVal, index: upIndex };
        }
      }
      if (downIndex >= 0 && downIndex < numbers.length) {
        const downVal = numbers[downIndex];
        if (!isDisabled(downVal)) {
          return { value: downVal, index: downIndex };
        }
      }
      upIndex++;
      downIndex--;
    }
    return null;
  });
  const onScroll = ahooks.useMemoizedFn((position) => {
    if (isArtificialScroll.current) return;
    if (currentValueChangedBy) return;
    clearTimeout(timeoutRef.current);
    const i = position.y / constant.CellHeight;
    if (i === Math.floor(i)) {
      const val2 = i >= numbers.length ? numbers.at(-1) : numbers[i];
      if (typeof val2 !== "undefined" && !isDisabled(val2)) {
        setVal(val2);
      } else if (typeof val2 !== "undefined" && isDisabled(val2)) {
        const nearest = findNearestValidValue(i);
        if (nearest) {
          setVal(nearest.value);
          setTimeout(() => {
            var _a;
            (_a = ref.current) == null ? void 0 : _a.scrollTo({ top: nearest.index * constant.CellHeight, behavior: "smooth" });
          }, 100);
        }
      }
    } else {
      timeoutRef.current = window.setTimeout(() => {
        const k = Math.round(i);
        const val2 = k >= numbers.length ? numbers.at(-1) : numbers[k];
        if (typeof val2 !== "undefined" && !isDisabled(val2)) {
          setVal(val2);
        } else if (typeof val2 !== "undefined" && isDisabled(val2)) {
          const nearest = findNearestValidValue(k);
          if (nearest) {
            setVal(nearest.value);
            setTimeout(() => {
              var _a;
              (_a = ref.current) == null ? void 0 : _a.scrollTo({ top: nearest.index * constant.CellHeight, behavior: "smooth" });
            }, 100);
          }
        }
      }, 300);
    }
  });
  const handleClickCell = ahooks.useMemoizedFn((e, i, val2) => {
    var _a;
    e.stopPropagation();
    e.preventDefault();
    if (!isDisabled(val2)) {
      (_a = ref.current) == null ? void 0 : _a.scrollTo({ top: i * constant.CellHeight, behavior: "smooth" });
    }
  });
  React.useEffect(() => {
    adjustScrollTop(val);
  }, [val]);
  return /* @__PURE__ */ jsxRuntime.jsxs(
    ScrollArea.ScrollArea,
    {
      viewportRef: ref,
      type: "never",
      styles: {
        viewport: {
          scrollSnapPointsY: `repeat(${constant.CellHeight}px)`,
          scrollSnapType: "y mandatory"
        }
      },
      onScrollPositionChange: onScroll,
      children: [
        numbers.map((i, index) => {
          const disabled = isDisabled(i);
          return /* @__PURE__ */ jsxRuntime.jsx(
            "div",
            {
              className: clsx(disabled ? classes.cellDisabled : classes.cell, i === curr && !disabled && classes.bold),
              onClick: (e) => handleClickCell(e, index, i),
              style: constant.CellStyle,
              children: render ? render(i) : i
            },
            i
          );
        }),
        lodashEs.range(6).map((i) => /* @__PURE__ */ jsxRuntime.jsx(Box.Box, { className: clsx(classes.cell, classes.cellPlaceholder), style: constant.CellStyle }, i))
      ]
    }
  );
}
function TimeScollerPicker({
  currentValue,
  currentValueChangedBy,
  start,
  end,
  onChange
}) {
  const options = React.useMemo(
    () => ({
      hour: getTimeRange({ curr: currentValue, start, end, type: "hour" }),
      minute: getTimeRange({ curr: currentValue, start, end, type: "minute" }),
      second: getTimeRange({ curr: currentValue, start, end, type: "second" })
    }),
    [currentValue, start, end]
  );
  const hourValue = React.useMemo(() => {
    return currentValue.hour();
  }, [currentValue]);
  const minuteValue = React.useMemo(() => {
    return currentValue.minute();
  }, [currentValue]);
  const secondValue = React.useMemo(() => {
    return currentValue.second();
  }, [currentValue]);
  const onHourChange = ahooks.useMemoizedFn((v) => {
    onChange == null ? void 0 : onChange([v, minuteValue, secondValue]);
  });
  const onMinuteChange = ahooks.useMemoizedFn((v) => {
    onChange == null ? void 0 : onChange([hourValue, v, secondValue]);
  });
  const onSecondChange = ahooks.useMemoizedFn((v) => {
    onChange == null ? void 0 : onChange([hourValue, minuteValue, v]);
  });
  return /* @__PURE__ */ jsxRuntime.jsxs(Flex.Flex, { mah: "100%", gap: 8, children: [
    /* @__PURE__ */ jsxRuntime.jsx(
      TimePickerScrollerColumn,
      {
        name: "hour",
        min: options.hour.min,
        max: options.hour.max,
        curr: hourValue,
        onChange: onHourChange,
        currentValueChangedBy
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      TimePickerScrollerColumn,
      {
        name: "minute",
        min: options.minute.min,
        max: options.minute.max,
        curr: minuteValue,
        onChange: onMinuteChange,
        currentValueChangedBy
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      TimePickerScrollerColumn,
      {
        name: "second",
        min: options.second.min,
        max: options.second.max,
        curr: secondValue,
        onChange: onSecondChange,
        currentValueChangedBy
      }
    )
  ] });
}
exports.TimeScollerPicker = TimeScollerPicker;
