import { useState } from 'react';

type IsCopied = boolean;
type CopiedValue = string | null;
type CopyFn = (text: string) => Promise<boolean>; // Return success

export type useCopyToClipboardReturnType = {
  isCopied: IsCopied;
  copiedText: CopiedValue;
  copy: CopyFn;
};

function useCopyToClipboard(): useCopyToClipboardReturnType {
  const [copiedText, setCopiedText] = useState<CopiedValue>(null);
  const [isCopied, setIsCopied] = useState<IsCopied>(false);

  const copy: CopyFn = async text => {
    if (!navigator?.clipboard) {
      console.warn('Clipboard not supported');
      setCopiedText(null);
      setIsCopied(false);
      return false;
    }

    // Try to save to clipboard then save it in the state if worked
    try {
      await navigator.clipboard.writeText(text);
      setCopiedText(text);
      setIsCopied(true);
      return true;
    } catch (error) {
      console.warn('Copy failed', error);
      setCopiedText(null);
      setIsCopied(false);
      return false;
    }
  };

  return { isCopied, copiedText, copy };
}

export default useCopyToClipboard;
