import { jsxs, jsx } from 'react/jsx-runtime';
import { useRef, useState, useMemo } from 'react';
import { format, setYear, setMonth, setDate, getUnixTime, setMinutes, setHours } from 'date-fns';
import { utcToZonedTime, zonedTimeToUtc } from 'date-fns-tz';
import { useDisclosure, PopoverTrigger, InputGroup, Input, InputRightElement, Flex, Box } from '@chakra-ui/react';
import { CalendarIcon } from '@chakra-ui/icons';
import RadioGroup from '../RadioGroup/RadioGroup.js';
import Calendar from './Calendar.js';
import PopoverContent from '../../Popover/PopoverContent.js';
import Popover from '../../Popover/Popover.js';
import Button from '../../Button/Button.js';

function isUnixTimestampMs(timestamp) {
  const numberOfDigits = timestamp.toString().length;
  return numberOfDigits >= 12;
}
const DateTimeInput = ({ onChange, value }) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const containerRef = useRef(null);
  const [mode, setMode] = useState("local");
  const [unixVal, setUnixVal] = useState("");
  const [defaultMonth, setDefaultMonth] = useState(value);
  const date = useMemo(() => {
    return isFinite(value) ? new Date(value) : /* @__PURE__ */ new Date();
  }, [value]);
  const selectedTimeZone = mode === "local" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "UTC";
  const dateTimeLocalized = 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__ */ jsxs(Popover, { trigger: null, isOpen, onClose, closeOnBlur: true, children: [
      /* @__PURE__ */ jsx(PopoverTrigger, { children: /* @__PURE__ */ jsxs(InputGroup, { children: [
        isOpen ? /* @__PURE__ */ jsx(
          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__ */ jsx(
          Input,
          {
            onClick: () => {
              setUnixVal("");
              setDefaultMonth(value);
              onOpen();
            },
            readOnly: true,
            value: `${format(dateTimeLocalized, "dd.MM.yyyy HH:mm:ss")} (${mode === "local" ? "Local" : "UTC"})`
          }
        ),
        /* @__PURE__ */ jsx(InputRightElement, { children: /* @__PURE__ */ jsx(CalendarIcon, { color: "gray.500" }) })
      ] }) }),
      /* @__PURE__ */ jsx(PopoverContent, { ref: containerRef, children: /* @__PURE__ */ jsxs(Flex, { gap: 2, flexDirection: "column", p: 2, children: [
        /* @__PURE__ */ jsx(
          Calendar,
          {
            defaultMonth: new Date(defaultMonth),
            style: { maxWidth: "100%" },
            mode: "single",
            selected: date,
            onSelect: (e) => {
              if (e) {
                const updatedDate = setYear(
                  setMonth(setDate(dateTimeLocalized, e.getDate()), e.getMonth()),
                  e.getFullYear()
                );
                onChange(getUnixTime(updatedDate) * 1e3);
              }
            }
          },
          `${defaultMonth}`
        ),
        /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", children: [
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "time",
              size: "sm",
              value: format(dateTimeLocalized, "HH:mm"),
              onChange: (e) => {
                const [hours, minutes] = e.target.value.split(":").map(Number);
                const zonedTime = utcToZonedTime(date, selectedTimeZone);
                const updatedTime = setMinutes(setHours(zonedTime, hours), minutes);
                const resultTime = zonedTimeToUtc(updatedTime, selectedTimeZone);
                const updated = getUnixTime(resultTime) * 1e3;
                onChange(updated);
              }
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "sm",
              onClick: () => {
                const newVal = Number(/* @__PURE__ */ new Date());
                setDefaultMonth(newVal);
                onChange(newVal);
              },
              children: "Now"
            }
          )
        ] }),
        /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(
          RadioGroup,
          {
            size: "sm",
            name: "mode",
            value: mode,
            onChange: (value2) => {
              setMode(value2);
            },
            options: [
              {
                label: "Local",
                value: "local"
              },
              {
                label: "UTC",
                value: "utc"
              }
            ]
          }
        ) })
      ] }) })
    ] })
  );
};

export { DateTimeInput as default };
//# sourceMappingURL=DateTimeInput.js.map
