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;
  noIcon?: boolean;
}

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

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

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

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