import { jsx } from "react/jsx-runtime";
import { useState, useRef, useMemo, useCallback, useEffect } from "react";
import Icon from "./Icon.js";
import { copyToClipboard } from "./utils/functions.js";
import Button from "./Button.js";
import { useToast } from "./Toast.js";
import Tooltip from "./Tooltip.js";
const TOOLTIP_LABEL_DEFAULT = "Copy to clipboard";
const TOOLTIP_LABEL_SUCCESS = "Copied!";
const ClipboardButton = ({
  copiedMessage = TOOLTIP_LABEL_SUCCESS,
  disabled,
  getContent,
  tooltipPlacement = "top",
  onCopy
}) => {
  const [iconName, setIconName] = useState("clipboard");
  const [tooltipLabel, setTooltipLabel] = useState(TOOLTIP_LABEL_DEFAULT);
  const [tooltipOpen, setTooltipOpen] = useState(false);
  const buttonRef = useRef(null);
  const { openToast } = useToast();
  const icon = useMemo(() => /* @__PURE__ */ jsx(Icon, { name: iconName, title: TOOLTIP_LABEL_DEFAULT }), [iconName]);
  const handleCopyToClipboard = useCallback(async () => {
    try {
      await copyToClipboard(getContent());
      setTooltipLabel(copiedMessage);
      setIconName("checkmark");
      onCopy == null ? void 0 : onCopy();
    } catch (e) {
      setTooltipOpen(false);
      openToast({
        description: e == null ? void 0 : e.message,
        severity: "Error",
        title: "Unable to Copy to Clipboard"
      });
    }
  }, [copiedMessage, getContent, onCopy, openToast]);
  useEffect(() => {
    const button = buttonRef.current;
    const onMouseEnter = () => {
      setTooltipLabel(TOOLTIP_LABEL_DEFAULT);
      setIconName("clipboard");
      setTooltipOpen(true);
    };
    const onMouseLeave = () => {
      setTooltipOpen(false);
      setIconName("clipboard");
    };
    button == null ? void 0 : button.addEventListener("mouseenter", onMouseEnter);
    button == null ? void 0 : button.addEventListener("mouseleave", onMouseLeave);
    return () => {
      button == null ? void 0 : button.removeEventListener("mouseenter", onMouseEnter);
      button == null ? void 0 : button.removeEventListener("mouseleave", onMouseLeave);
    };
  }, []);
  return /* @__PURE__ */ jsx(Tooltip, { content: tooltipLabel, open: tooltipOpen, placement: tooltipPlacement, children: /* @__PURE__ */ jsx(
    Button,
    {
      "aria-label": tooltipLabel,
      disabled,
      icon,
      ref: buttonRef,
      onClick: handleCopyToClipboard
    }
  ) });
};
export {
  TOOLTIP_LABEL_DEFAULT,
  ClipboardButton as default
};
