import { useRef, useState } from "react";
import styles from "./ClickToCopy.module.css";

const ClickToCopy = ({ text, children }) => {
  const textareaRef = useRef(null);
  const [copied, setCopied] = useState(false);
  const onClick = () => {
    textareaRef.current.select();
    document.execCommand("copy");
    setCopied(true);
  };

  return (
    <div className={styles.container}>
      <span
        role="button"
        tabIndex="0"
        className={styles.underlined}
        onClick={onClick}
        onFocus={() => setCopied(false)}
        onKeyDown={({ key }) => {
          if (key === "Enter") {
            onClick();
          }
        }}
        onMouseOver={() => setCopied(false)}
      >
        {children ?? text}
      </span>
      <span className={styles.tooltip}>
        {copied ? "Copied!" : "Click to Copy"}
      </span>
      <textarea
        className={styles.invisible}
        ref={textareaRef}
        value={text ?? children}
        readOnly
      />
    </div>
  );
};

export default ClickToCopy;
