import Bold from '@tiptap/extension-bold';
import Document from '@tiptap/extension-document';
import Highlight from '@tiptap/extension-highlight';
import Italic from '@tiptap/extension-italic';
import Paragraph from '@tiptap/extension-paragraph';
import Strike from '@tiptap/extension-strike';
import Text from '@tiptap/extension-text';
import TextAlign from '@tiptap/extension-text-align';
import { Color, FontSize, TextStyle } from '@tiptap/extension-text-style';
import Underline from '@tiptap/extension-underline';
import { UndoRedo } from '@tiptap/extensions';
import { EditorContent, useEditor } from '@tiptap/react';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { changeBadgeSettingProperties } from '../../../../../../../features/badges/badgesSlice';
import EditorToolbar from './components/EditorToolbar';

const TextEditor = () => {
  const dispatch = useDispatch();
  const { badge_settings } = useSelector((state) => state.badges);

  const editor = useEditor({
    extensions: [
      Document,
      Paragraph,
      Text,
      Bold,
      Italic,
      Underline,
      TextStyle,
      FontSize,
      Color,
      UndoRedo,
      Strike,
      TextAlign.configure({
        types: ['paragraph'],
      }),
      Highlight.configure({
        multicolor: true,
        HTMLAttributes: {
          class: 'wmx-text-highlight',
        },
      }),
    ],
    content: '',
    onUpdate: ({ editor }) => {
      const html = editor.getHTML();
      if (html !== badge_settings.text) {
        dispatch(changeBadgeSettingProperties({ name: 'text', value: html }));
      }
    },
  });

  useEffect(() => {
    if (editor && badge_settings.text) {
      const currentHTML = editor.getHTML();
      if (!editor.isFocused && currentHTML !== badge_settings.text) {
        editor.commands.setContent(badge_settings.text, false);
      }
    }
  }, [badge_settings.text, editor]);

  if (!editor) {
    return null;
  }

  return (
    <div className='wmx-border wmx-border-gray-200 wmx-rounded-lg wmx-shadow-sm wmx-bg-white'>
      <EditorToolbar editor={editor} />
      <div
        style={{
          background: badge_settings.background,
        }}
        className='wmx-p-2 wmx-min-h-[120px] wmx-rounded-lg  wmx-focus:outline-none wmx-prose wmx-max-w-none'
      >
        <EditorContent editor={editor} />
      </div>
    </div>
  );
};

export default TextEditor;
