import { useState } from 'react';
import { useEditor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import TextAlign from '@tiptap/extension-text-align';
import Blockquote from '@tiptap/extension-blockquote';
import Highlight from '@tiptap/extension-highlight';
import Image from '@tiptap/extension-image';

export const useContentEditor = (content = '') => {
  const [selectedImage, setSelectedImage] = useState<string | null>(null);

  const editor = useEditor({
    extensions: [
      StarterKit.configure({
        blockquote: false, // Отключаем дефолтный
      }),
      Blockquote.configure({
        HTMLAttributes: {
          class: 'border-l-4 border-gray-300 pl-4 italic',
        },
      }),
      TextAlign.configure({
        types: ['heading', 'paragraph'],
      }),
      Highlight,
      Image.configure({
        inline: false,
        HTMLAttributes: {
          class: 'resizable-image',
        },
      }),
    ],
    content,
    editorProps: {
      attributes: {
        class: 'prose prose-lg focus:outline-none min-h-[300px] max-w-none',
      },
    },
    onUpdate: ({ editor }) => {
      const { from, to } = editor.state.selection;
      let isImageSelected = false;

      editor.state.doc.nodesBetween(from, to, (node) => {
        if (node.type.name === 'image') {
          setSelectedImage(node.attrs.src);
          isImageSelected = true;
        }
      });

      if (!isImageSelected) {
        setSelectedImage(null);
      }
    },
  });

  const updateImageSize = (delta: number) => {
    if (selectedImage) {
      const attrs = editor?.getAttributes('image');
      if (!attrs) return;
      const newWidth = Math.max((parseInt(attrs.width) || 100) + delta, 50);
      editor?.chain().focus().updateAttributes('image', { width: newWidth }).run();
    }
  };

  return { editor, selectedImage, updateImageSize };
};
