'use strict';

var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var dateFns = require('date-fns');
var dateFnsTz = require('date-fns-tz');
var react = require('@chakra-ui/react');
var icons = require('@chakra-ui/icons');
var RadioGroup = require('../RadioGroup/RadioGroup.cjs');
var Calendar = require('./Calendar.cjs');
var PopoverContent = require('../../Popover/PopoverContent.cjs');
var Popover = require('../../Popover/Popover.cjs');
var Button = require('../../Button/Button.cjs');

function isUnixTimestampMs(timestamp) {
  const numberOfDigits = timestamp.toString().length;
  return numberOfDigits >= 12;
}
const DateTimeInput = ({ onChange, value }) => {
  const { isOpen, onOpen, onClose } = react.useDisclosure();
  const containerRef = React.useRef(null);
  const [mode, setMode] = React.useState("local");
  const [unixVal, setUnixVal] = React.useState("");
  const [defaultMonth, setDefaultMonth] = React.useState(value);
  const date = React.useMemo(() => {
    return isFinite(value) ? new Date(value) : /* @__PURE__ */ new Date();
  }, [value]);
  const selectedTimeZone = mode === "local" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "UTC";
  const dateTimeLocalized = dateFnsTz.utcToZonedTime(date, selectedTimeZone);
  return (
    // We want to avoid both Hover and Click behaviours when working in manual mode
    // https://github.com/chakra-ui/chakra-ui/issues/4733
    // @ts-ignore
    /* @__PURE__ */ jsxRuntime.jsxs(Popover, { trigger: null, isOpen, onClose, closeOnBlur: true, children: [
      /* @__PURE__ */ jsxRuntime.jsx(react.PopoverTrigger, { children: /* @__PURE__ */ jsxRuntime.jsxs(react.InputGroup, { children: [
        isOpen ? /* @__PURE__ */ jsxRuntime.jsx(
          react.Input,
          {
            type: "number",
            placeholder: "Enter unix timestamp",
            onChange: (e) => setUnixVal(e.target.value),
            value: unixVal,
            onKeyDown: (e) => {
              if (e.key === "Enter") {
                e.preventDefault();
                const possibleTimestamp = Number(unixVal);
                if (Number.isFinite(possibleTimestamp)) {
                  if (isUnixTimestampMs(possibleTimestamp)) {
                    onChange(possibleTimestamp);
                  } else {
                    onChange(possibleTimestamp * 1e3);
                  }
                }
                onClose();
              }
            },
            onBlur: (event) => {
              var _a;
              if (!((_a = containerRef.current) == null ? void 0 : _a.contains(event.relatedTarget))) {
                onClose();
              }
            }
          }
        ) : /* @__PURE__ */ jsxRuntime.jsx(
          react.Input,
          {
            onClick: () => {
              setUnixVal("");
              setDefaultMonth(value);
              onOpen();
            },
            readOnly: true,
            value: `${dateFns.format(dateTimeLocalized, "dd.MM.yyyy HH:mm:ss")} (${mode === "local" ? "Local" : "UTC"})`
          }
        ),
        /* @__PURE__ */ jsxRuntime.jsx(react.InputRightElement, { children: /* @__PURE__ */ jsxRuntime.jsx(icons.CalendarIcon, { color: "gray.500" }) })
      ] }) }),
      /* @__PURE__ */ jsxRuntime.jsx(PopoverContent, { ref: containerRef, children: /* @__PURE__ */ jsxRuntime.jsxs(react.Flex, { gap: 2, flexDirection: "column", p: 2, children: [
        /* @__PURE__ */ jsxRuntime.jsx(
          Calendar,
          {
            defaultMonth: new Date(defaultMonth),
            style: { maxWidth: "100%" },
            mode: "single",
            selected: date,
            onSelect: (e) => {
              if (e) {
                const updatedDate = dateFns.setYear(
                  dateFns.setMonth(dateFns.setDate(dateTimeLocalized, e.getDate()), e.getMonth()),
                  e.getFullYear()
                );
                onChange(dateFns.getUnixTime(updatedDate) * 1e3);
              }
            }
          },
          `${defaultMonth}`
        ),
        /* @__PURE__ */ jsxRuntime.jsxs(react.Flex, { gap: 2, alignItems: "center", children: [
          /* @__PURE__ */ jsxRuntime.jsx(
            react.Input,
            {
              type: "time",
              size: "sm",
              value: dateFns.format(dateTimeLocalized, "HH:mm"),
              onChange: (e) => {
                const [hours, minutes] = e.target.value.split(":").map(Number);
                const zonedTime = dateFnsTz.utcToZonedTime(date, selectedTimeZone);
                const updatedTime = dateFns.setMinutes(dateFns.setHours(zonedTime, hours), minutes);
                const resultTime = dateFnsTz.zonedTimeToUtc(updatedTime, selectedTimeZone);
                const updated = dateFns.getUnixTime(resultTime) * 1e3;
                onChange(updated);
              }
            }
          ),
          /* @__PURE__ */ jsxRuntime.jsx(
            Button,
            {
              size: "sm",
              onClick: () => {
                const newVal = Number(/* @__PURE__ */ new Date());
                setDefaultMonth(newVal);
                onChange(newVal);
              },
              children: "Now"
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntime.jsx(react.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(
          RadioGroup,
          {
            size: "sm",
            name: "mode",
            value: mode,
            onChange: (value2) => {
              setMode(value2);
            },
            options: [
              {
                label: "Local",
                value: "local"
              },
              {
                label: "UTC",
                value: "utc"
              }
            ]
          }
        ) })
      ] }) })
    ] })
  );
};

module.exports = DateTimeInput;
//# sourceMappingURL=DateTimeInput.cjs.map
