import { useEffect, useMemo } from 'react';

import { useEditor } from '@tiptap/react';

import { type Member } from 'src/pages/dashboard/Conversations/types';
import {
  convertMessageToTipTapFormat,
  extractHighlightedSpans,
  formatValueMessage,
  getIsMention,
} from 'src/pages/dashboard/Conversations/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useExtensions from './useExtensions';

type UseHandlerEditorProps = {
  placeholder: string;
  members: Member[];
  isPopper?: boolean;
  handlePaste?: (event: ClipboardEvent) => void;
  maxLength: number;
  isGroupConversation: boolean;
  content: string | object;
  disabled?: boolean;
  clearOnSubmit: boolean;
  messageToReplyTs?: string;
  onChange: (value: string) => void;
};

export const useHandlerEditor = ({
  placeholder,
  members,
  isPopper,
  handlePaste,
  maxLength,
  isGroupConversation,
  content,
  disabled,
  clearOnSubmit,
  messageToReplyTs,
  onChange,
}: UseHandlerEditorProps) => {
  const { t } = useLokaliseTranslation('chat');
  const extensions = useExtensions({
    placeholder: t(placeholder),
    members,
    isPopper,
    handlePaste,
    maxLength,
    isGroupConversation,
  });

  const processedContent = useMemo(() => {
    if (typeof content === 'string' && getIsMention(content)) {
      const mentionSpans = extractHighlightedSpans(content);
      return convertMessageToTipTapFormat({
        messageText: content,
        mentionSpans,
        t,
      });
    }
    return content;
  }, [members.length]);

  const editor = useEditor(
    {
      extensions,
      content: processedContent,
      editable: !disabled,
    },
    [members.length],
  );

  useEffect(() => {
    if (!editor || !onChange) return;
    const updateHandler = () => {
      const text = formatValueMessage(editor);
      onChange(editor?.isEmpty ? '' : text);
    };

    editor.on('update', updateHandler);

    return () => {
      editor.off('update', updateHandler);
    };
  }, [editor, onChange]);

  useEffect(() => {
    if (!editor) return;
    editor.setEditable(!disabled);
    editor.commands.focus('end');
    if (disabled && clearOnSubmit) {
      editor.commands.clearContent();
    }
  }, [editor, disabled, messageToReplyTs]);

  useEffect(() => {
    if (!editor) return;
    const isContentEmpty = content === '' || content === undefined;
    if (isContentEmpty && !editor.isEmpty) {
      editor.commands.clearContent();
    }
  }, [editor, content]);

  return {
    editor,
  };
};
