import React, { useRef, useState } from "react";

const tooltipClass = "click-to-copy__tooltip";
const tooltipVisClass = `${tooltipClass}--visible`;

export default ({ text }) => {
  const textareaRef = useRef(null);
  const [hovered, setHovered] = useState(false);
  const [copied, setCopied] = useState(false);
  const copyText = () => {
    textareaRef.current.select();
    document.execCommand("copy");
    setCopied(true);
  };

  const hoveredClass = hovered ? tooltipVisClass : "";

  return (
    <div className="click-to-copy">
      <span
        className="click-to-copy__text"
        onClick={copyText}
        onMouseOver={() => {setCopied(false); setHovered(true)}}
        onMouseOut={() => setHovered(false)}
      >
        {text}
      </span>
      <span className={`${tooltipClass} ${hoveredClass}`}>
        {copied ? "Copied!" : "Click to Copy"}
      </span>
      <textarea
        ref={textareaRef}
        className="click-to-copy__textarea"
        value={text}
        readOnly
      />
    </div>
  )
}
