/* eslint-disable jsx-a11y/anchor-is-valid */
// @flow
import React, { useRef } from 'react';
import styled from 'styled-components';

import CopyIcon from '../../Icons/CopyIcon';


// Used to hide the textbox
// Setting display to none or visibility to hidden is not supported by the execCommand method
const TextAreaBox = styled.textarea`
  position: absolute;
  left: -999em;
`;


const Link = styled.a`
 background-color: white;
  border: none;
  font-size: 0;
  cursor: pointer;
  padding: 0;
  text-decoration: none;
`;

type Props = {
  url: string,
  dataGtmEventContext: string,
  dataGtmEventType: string,
}

const ClipboardCopy = ({
  url,
  dataGtmEventContext,
  dataGtmEventType,
}: Props) => {
  const textAreaRef: { current: any } = useRef(null);

  const copyToClipboard = (e) => {
    textAreaRef.current.select();
    document.execCommand('copy');
    e.preventDefault();
  };

  return (
    <>
      {
        // Check if the copy command is supported
        // $FlowFixMe
        document.queryCommandSupported('copy') && (
          <div>
            <Link
              href="#"
              onClick={copyToClipboard}
              data-gtm-event-context={dataGtmEventContext}
              data-gtm-event-type={dataGtmEventType}
              className="gtm-trackable"
            >
              copy
              <CopyIcon />
            </Link>
          </div>
        )
      }
      <TextAreaBox ref={textAreaRef} aria-hidden="true" defaultValue={url} />
    </>
  );
};

export default ClipboardCopy;
