import React, { FC, useState, useEffect } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { Icon } from '../Icon';
import * as icons from '../../assets/images/icons';
import * as sc from './styles';

export interface Props {
  width?: string | number;
  height?: string | number;
  color?: string;
  copyText: string;
  tooltip?: string;
}

export const CopyableText: FC<Props> = ({
  width,
  height,
  color,
  copyText,
  tooltip,
  children,
}) => {
  const [copied, setCopied] = useState(false);
  const [timerRef, setTimerRef] = useState(0);

  useEffect(() => {
    return () => {
      if (timerRef !== 0) clearTimeout(timerRef);
    };
  }, [timerRef]);

  const handleCopyClick = () => {
    setCopied(true);
    setTimerRef(
      setTimeout(() => {
        setCopied(false);
      }, 2000)
    );
  };

  return (
    <CopyToClipboard text={copyText}>
      <sc.CopyText
        onClick={handleCopyClick}
        copied={copied}
        tooltip={tooltip || 'Copied'}
      >
        {children}
        <Icon
          Asset={icons.SvgCopy}
          width={width || 14}
          height={height || 14}
          color={color || 'gray.2'}
          ml="s"
        />
      </sc.CopyText>
    </CopyToClipboard>
  );
};
