import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import {
  AUTO_HIDE_DURATION,
  CONVERSATIONS_THREAD_FOOTER_ID,
} from 'src/pages/dashboard/Conversations/constants';
import { type ConversationMessage } from 'src/pages/dashboard/Conversations/types';
import {
  detectInputPosition,
  getMessageContentType,
  isImageAttachment,
  replaceMentionIdsWithFullName,
} from 'src/pages/dashboard/Conversations/utils';
import { getCopyImage } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

export const useMessageCopy = ({
  attachments = [],
  text = '',
  hu_data,
}: ConversationMessage) => {
  const { enqueueSnackbar } = useHuSnackbar();
  const { t } = useLokaliseTranslation('chat');
  const { hasOnlyOneImage } = getMessageContentType({
    attachments,
    text,
  });

  const textWithFullNames = replaceMentionIdsWithFullName(
    text,
    hu_data?.highlighted_spans,
  );

  const handleCopy = async () => {
    try {
      let clipboardItem: ClipboardItem;
      const textPlain = 'text/plain';
      if (
        hasOnlyOneImage &&
        isImageAttachment(attachments[0]) &&
        !text.length
      ) {
        const url = attachments[0].image_url;
        const blob = await getCopyImage(url);
        clipboardItem = new ClipboardItem({ [blob.type]: blob });
      } else {
        const textBlob = new Blob([textWithFullNames], { type: textPlain });
        clipboardItem = new ClipboardItem({ [textPlain]: textBlob });
      }

      await navigator.clipboard.write([clipboardItem]);

      enqueueSnackbar({
        title: t('messages.message_copied'),
        variant: 'success',
        autoHideDuration: AUTO_HIDE_DURATION,
        spacing: {
          bottom: detectInputPosition(CONVERSATIONS_THREAD_FOOTER_ID) || 0,
        },
      });
    } catch {
      enqueueSnackbar({
        title: t('messages.failed_to_copy_message'),
        variant: 'error',
        autoHideDuration: AUTO_HIDE_DURATION,
        spacing: {
          bottom: detectInputPosition(CONVERSATIONS_THREAD_FOOTER_ID) || 0,
        },
      });
    }
  };

  return { handleCopy };
};
