import { useState } from 'react';

import { useLokaliseTranslation } from 'src/utils/i18n';

export const useCopyUrl = () => {
  const [copied, setCopied] = useState(false);

  const { t } = useLokaliseTranslation('deeplinks');

  const getCopyString = (type: string) =>
    t(type) ? t('copy', { resource: t(type) }) : t('copy_link');

  const getCopiedString = (copyLinkText = '') =>
    copied ? t('copied') : copyLinkText;

  const resetCopiedDelayed = (delay: number = 1000) =>
    setTimeout(() => setCopied(false), delay);

  const copyUrlToClipboard = async (route?: string, withOrigin = true) => {
    let path = document.URL;

    if (route) {
      path = withOrigin ? window.location.origin + route : route;
    }

    await navigator.clipboard.writeText(path);
    setCopied(true);
  };

  return {
    copied,
    getCopyString,
    getCopiedString,
    copyUrlToClipboard,
    resetCopiedDelayed,
  };
};

export default useCopyUrl;
