import React, { useState, useEffect } from 'react';
import CopyToClipboardContainer, {
  CopyToClipboardContainerProps,
} from '@digigov/react-core/CopyToClipboardContainer';
import CopyToClipboardMessage from '@digigov/react-core/CopyToClipboardMessage';
import { useTranslation } from '@digigov/ui/i18n';
import NormalText from '@digigov/ui/typography/NormalText';

export interface CopyToClipboardProps extends CopyToClipboardContainerProps {
  text: string;
  message?: string;
  timeout?: number;
  onCopy?: () => void;
}

export const CopyToClipboard = React.forwardRef<
  HTMLDivElement,
  CopyToClipboardProps
>(function CopyToClipboard(
  {
    text,
    variant = 'tooltip',
    tooltipAlign = 'right',
    message,
    dense,
    onCopy,
    timeout = 3000,
    children,
  },
  ref
) {
  const [enabled, setEnabled] = useState(false);
  const { t } = useTranslation();

  useEffect(() => {
    const timeoutInstance = setTimeout(() => {
      if (enabled) setEnabled(false);
    }, timeout);

    return () => clearTimeout(timeoutInstance);
  }, [enabled]);

  function copyToClipboard() {
    if (onCopy) onCopy();
    navigator.clipboard.writeText(text);
    setEnabled(true);
  }

  return (
    <CopyToClipboardContainer
      onClick={copyToClipboard}
      variant={variant}
      tooltipAlign={tooltipAlign}
      ref={ref}
      dense={dense}
    >
      {children}
      {enabled && (
        <CopyToClipboardMessage enabled={enabled} role="tooltip">
          <NormalText>{message || t('copy-to-clipboard.message')}</NormalText>
        </CopyToClipboardMessage>
      )}
    </CopyToClipboardContainer>
  );
});

export default CopyToClipboard;

export { CopyToClipboardContainer, CopyToClipboardMessage };
