import { jsxs, jsx } from "react/jsx-runtime";
import { useMemoizedFn } from "ahooks";
import { useState, useMemo } from "react";
import { IconClock } from "../../icons/index.mjs";
/* empty css                                                                                                                                                                                       */
/* empty css                                                                                                                                                                                        */
/* empty css                                                                                                                                                                                                */
/* empty css                                                                                                                                                                                           */
/* empty css                                                                                                                                                                                           */
import { Typography } from "../../primitive/Typography/index.mjs";
import { dayjs } from "../../utils/dayjs.mjs";
import { DEFAULT_TIME_FORMAT } from "../TimeRangePicker/helpers.mjs";
import { TimeScollerPicker } from "./TimeScollerPicker.mjs";
import { useDisclosure } from "../../node_modules/.pnpm/@mantine_hooks@7.15.2_react@18.3.1/node_modules/@mantine/hooks/esm/use-disclosure/use-disclosure.mjs";
import { useUncontrolled } from "../../node_modules/.pnpm/@mantine_hooks@7.15.2_react@18.3.1/node_modules/@mantine/hooks/esm/use-uncontrolled/use-uncontrolled.mjs";
import { Popover } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Popover/Popover.mjs";
import { TextInput } from "../../primitive/TextInput/TextInput.mjs";
import { Loader } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Loader/Loader.mjs";
import { Box } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/core/Box/Box.mjs";
import { Stack } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Stack/Stack.mjs";
import { Group } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Group/Group.mjs";
import { DatePicker } from "../../node_modules/.pnpm/@mantine_dates@7.15.2_@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hoo_pt67admfm6wboa3vchveewq6zq/node_modules/@mantine/dates/esm/components/DatePicker/DatePicker.mjs";
import { Divider } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Divider/Divider.mjs";
import { TimeInput } from "../../node_modules/.pnpm/@mantine_dates@7.15.2_@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hoo_pt67admfm6wboa3vchveewq6zq/node_modules/@mantine/dates/esm/components/TimeInput/TimeInput.mjs";
import { Flex } from "../../node_modules/.pnpm/@mantine_core@7.15.2_patch_hash_jclkxeaefn6uz54h34k3r3yjsq_@mantine_hooks@7.15.2_react@18.3.1_szqfuioo5damkjdixckhzmwycq/node_modules/@mantine/core/esm/components/Flex/Flex.mjs";
const DateTimePicker = ({
  placeholder = "Select time",
  format = DEFAULT_TIME_FORMAT,
  defaultValue,
  value,
  startDate = dayjs().subtract(10, "year").toDate(),
  endDate = dayjs().add(10, "year").toDate(),
  onChange,
  disable = false,
  utcOffset = dayjs().utcOffset(),
  withinPortal = true,
  sx,
  loading = false,
  size
}) => {
  const [opened, { close, open }] = useDisclosure(false);
  const [currentValue, setCurrentValue] = useUncontrolled({
    value: value ? dayjs(value) : void 0,
    defaultValue: defaultValue ? dayjs(defaultValue) : dayjs(),
    onChange: (v) => {
      onChange == null ? void 0 : onChange(v.toDate());
    }
  });
  const [currentValueChangedBy, setCurrentValueChangedBy] = useState(null);
  const updateCurrentValue = useMemoizedFn((val, from) => {
    let next = val;
    if (!next.isValid()) {
      return;
    }
    if ((currentValue == null ? void 0 : currentValue.unix()) === next.unix()) {
      return;
    }
    if (startDate && next.isBefore(startDate)) {
      next = dayjs(startDate);
    } else if (endDate && next.isAfter(endDate)) {
      next = dayjs(endDate);
    }
    setCurrentValue(next);
    setCurrentValueChangedBy(from);
    setTimeout(() => {
      setCurrentValueChangedBy(null);
    }, 20);
  });
  const inputStr = currentValue.format(format);
  const utcStr = useMemo(() => {
    const h = Math.floor(utcOffset / 60);
    const m = utcOffset % 60;
    return `UTC${h >= 0 ? "+" : "-"}${Math.abs(h)}:${m < 10 ? "0" : ""}${m}`;
  }, [utcOffset]);
  const calendarChange = useMemoizedFn((v) => {
    let next = currentValue;
    next = next.utcOffset(utcOffset).year(v.getFullYear()).month(v.getMonth()).date(v.getDate());
    updateCurrentValue(next, "calendar");
  });
  const timeInputChange = useMemoizedFn((e) => {
    const originVal = e.currentTarget.value;
    const v = dayjs(originVal, "HH:mm:ss").toDate();
    let next = currentValue;
    next = next.utcOffset(utcOffset).hour(v.getHours()).minute(v.getMinutes()).second(v.getSeconds());
    updateCurrentValue(next, "timeInput");
  });
  const timeScrollPickerChange = useMemoizedFn((v) => {
    const [h, m, s] = v;
    let next = currentValue;
    next = next.utcOffset(utcOffset).hour(h).minute(m).second(s);
    updateCurrentValue(next, "timeScroller");
  });
  return /* @__PURE__ */ jsxs(
    Popover,
    {
      position: "bottom-end",
      opened,
      withinPortal,
      shadow: "md",
      closeOnClickOutside: true,
      onChange: (opened2) => {
        if (opened2) {
          open();
        } else {
          close();
        }
      },
      children: [
        /* @__PURE__ */ jsx(Popover.Target, { children: /* @__PURE__ */ jsx(
          TextInput,
          {
            readOnly: true,
            disabled: disable,
            placeholder,
            value: inputStr,
            rightSection: loading ? /* @__PURE__ */ jsx(Loader, { size: "xs" }) : /* @__PURE__ */ jsx(Box, { component: IconClock, size: 18, c: "carbon.6" }),
            sx,
            size,
            onClick: open
          }
        ) }),
        /* @__PURE__ */ jsx(Popover.Dropdown, { children: /* @__PURE__ */ jsxs(Stack, { children: [
          /* @__PURE__ */ jsxs(Group, { align: "flex-start", children: [
            /* @__PURE__ */ jsx(
              DatePicker,
              {
                minDate: startDate,
                maxDate: endDate,
                value: currentValue.toDate(),
                onChange: calendarChange,
                withCellSpacing: false,
                size: "md"
              }
            ),
            /* @__PURE__ */ jsx(Divider, { orientation: "vertical", mt: -12, mb: -16 }),
            /* @__PURE__ */ jsxs(Stack, { justify: "flex-start", children: [
              /* @__PURE__ */ jsx(
                TimeInput,
                {
                  withSeconds: true,
                  value: currentValue.format("HH:mm:ss"),
                  onChange: timeInputChange,
                  size: "sm",
                  w: 112,
                  styles: {
                    input: {
                      height: 30
                    }
                  }
                }
              ),
              /* @__PURE__ */ jsxs(
                Box,
                {
                  pos: "relative",
                  fz: 14,
                  fw: 400,
                  h: 224,
                  sx: (theme) => ({ color: theme.colors.carbon[8], overflow: "hidden", zIndex: 9999 }),
                  children: [
                    /* @__PURE__ */ jsxs(Flex, { mah: "100%", gap: 8, children: [
                      /* @__PURE__ */ jsx(
                        Box,
                        {
                          bg: "carbon.3",
                          pos: "absolute",
                          top: 0,
                          left: 0,
                          h: 32,
                          w: 32,
                          sx: (theme) => ({ zIndex: -1, borderRadius: theme.defaultRadius, pointerEvents: "none" })
                        }
                      ),
                      /* @__PURE__ */ jsx(
                        Box,
                        {
                          bg: "carbon.3",
                          pos: "absolute",
                          top: 0,
                          left: 40,
                          h: 32,
                          w: 32,
                          sx: (theme) => ({ zIndex: -1, borderRadius: theme.defaultRadius, pointerEvents: "none" })
                        }
                      ),
                      /* @__PURE__ */ jsx(
                        Box,
                        {
                          bg: "carbon.3",
                          pos: "absolute",
                          top: 0,
                          left: 80,
                          h: 32,
                          w: 32,
                          sx: (theme) => ({ zIndex: -1, borderRadius: theme.defaultRadius, pointerEvents: "none" })
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsx(
                      TimeScollerPicker,
                      {
                        currentValue,
                        currentValueChangedBy,
                        onChange: timeScrollPickerChange,
                        start: startDate,
                        end: endDate,
                        utcOffset
                      }
                    )
                  ]
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsx(Divider, { mx: -16 }),
          /* @__PURE__ */ jsx(Group, { children: /* @__PURE__ */ jsxs(Typography, { size: "sm", children: [
            "Use",
            " ",
            /* @__PURE__ */ jsx(Typography, { fw: 600, component: "span", children: utcStr }),
            " ",
            "from your local time zone"
          ] }) })
        ] }) })
      ]
    }
  );
};
const TimePicker = ({
  value,
  onChange,
  defaultValue,
  disable = false,
  sx,
  size,
  minTime,
  maxTime,
  withinPortal,
  withArrow,
  position,
  shadow,
  ...rest
}) => {
  const [currentValue, setCurrentValue] = useUncontrolled({
    value: value ? dayjs(value, "HH:mm:ss") : void 0,
    defaultValue: defaultValue ? dayjs(defaultValue, "HH:mm:ss") : dayjs(),
    onChange: (v) => {
      onChange == null ? void 0 : onChange(v.format("HH:mm:ss"));
    }
  });
  const [currentValueChangedBy, setCurrentValueChangedBy] = useState(null);
  const startDate = useMemo(() => dayjs(minTime, "HH:mm:ss"), [minTime]);
  const endDate = useMemo(() => dayjs(maxTime, "HH:mm:ss"), [maxTime]);
  const updateCurrentValue = useMemoizedFn((val, from) => {
    let next = val;
    if (!next.isValid()) {
      return;
    }
    if ((currentValue == null ? void 0 : currentValue.unix()) === next.unix()) {
      return;
    }
    if (startDate && next.isBefore(startDate)) {
      next = dayjs(startDate);
    } else if (endDate && next.isAfter(endDate)) {
      next = dayjs(endDate);
    }
    setCurrentValue(next);
    setCurrentValueChangedBy(from);
    setTimeout(() => {
      setCurrentValueChangedBy(null);
    }, 20);
  });
  const timeInputChange = useMemoizedFn((e) => {
    const originVal = e.currentTarget.value;
    const v = dayjs(originVal, "HH:mm:ss").toDate();
    let next = currentValue;
    next = next.hour(v.getHours()).minute(v.getMinutes()).second(v.getSeconds());
    updateCurrentValue(next, "timeInput");
  });
  const timeScrollPickerChange = useMemoizedFn((v) => {
    const [h, m, s] = v;
    let next = currentValue;
    next = next.hour(h).minute(m).second(s);
    updateCurrentValue(next, "timeScroller");
  });
  return /* @__PURE__ */ jsxs(Popover, { withinPortal, withArrow, position, shadow, children: [
    /* @__PURE__ */ jsx(Popover.Target, { children: /* @__PURE__ */ jsx(
      TimeInput,
      {
        ...rest,
        disabled: disable,
        withSeconds: true,
        value: currentValue.format("HH:mm:ss"),
        onChange: timeInputChange,
        size,
        sx,
        rightSection: /* @__PURE__ */ jsx(IconClock, { size: 16, c: "carbon.7" })
      }
    ) }),
    /* @__PURE__ */ jsx(Popover.Dropdown, { children: /* @__PURE__ */ jsxs(
      Box,
      {
        pos: "relative",
        fz: 14,
        fw: 400,
        h: 224,
        sx: (theme) => ({ color: theme.colors.carbon[8], overflow: "hidden", zIndex: 9999 }),
        children: [
          /* @__PURE__ */ jsxs(Flex, { mah: "100%", gap: 8, children: [
            /* @__PURE__ */ jsx(
              Box,
              {
                bg: "carbon.3",
                pos: "absolute",
                top: 0,
                left: 0,
                h: 32,
                w: 32,
                sx: (theme) => ({ zIndex: -1, borderRadius: theme.defaultRadius, pointerEvents: "none" })
              }
            ),
            /* @__PURE__ */ jsx(
              Box,
              {
                bg: "carbon.3",
                pos: "absolute",
                top: 0,
                left: 40,
                h: 32,
                w: 32,
                sx: (theme) => ({ zIndex: -1, borderRadius: theme.defaultRadius, pointerEvents: "none" })
              }
            ),
            /* @__PURE__ */ jsx(
              Box,
              {
                bg: "carbon.3",
                pos: "absolute",
                top: 0,
                left: 80,
                h: 32,
                w: 32,
                sx: (theme) => ({ zIndex: -1, borderRadius: theme.defaultRadius, pointerEvents: "none" })
              }
            )
          ] }),
          /* @__PURE__ */ jsx(
            TimeScollerPicker,
            {
              currentValue,
              currentValueChangedBy,
              onChange: timeScrollPickerChange,
              start: startDate.toDate(),
              end: endDate.toDate()
            }
          )
        ]
      }
    ) })
  ] });
};
export {
  DateTimePicker,
  TimePicker
};
