import { forwardRef, useEffect, useImperativeHandle } from 'react';
import { EditorContent, useEditor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Link from '@tiptap/extension-link';
import Placeholder from '@tiptap/extension-placeholder';
import Image from '@tiptap/extension-image';
import { Button, Stack } from '@mui/material';

export type RichEditorHandle = {
  insertImage: (src: string, alt?: string) => void;
  insertHtmlAtCursor: (html: string) => void;
};

type Props = {
  value: string;
  onChange: (html: string) => void;
  placeholder?: string;
};

const RichEditor = forwardRef<RichEditorHandle, Props>(({ value, onChange, placeholder }, ref) => {
  const editor = useEditor({
    extensions: [
      StarterKit,
      Link.configure({ openOnClick: true }),
      Placeholder.configure({ placeholder: placeholder ?? 'Write something…' }),
      Image.configure({ inline: false, allowBase64: false }),
    ],
    content: value ?? '',
    onUpdate: ({ editor }) => onChange(editor.getHTML()),
    editorProps: { attributes: { class: 'tiptap-content' } },
  });

  useImperativeHandle(ref, () => ({
    insertImage: (src: string, alt?: string) => {
      if (!editor) return;
      editor.chain().focus().setImage({ src, alt }).run();
    },
    insertHtmlAtCursor: (html: string) => {
      if (!editor) return;
      editor.chain().focus().insertContent(html).run();
    },
  }), [editor]);

  useEffect(() => {
    if (editor && value !== editor.getHTML()) {
      editor.commands.setContent(value ?? '', { emitUpdate: false });
    }
  }, [value, editor]);

  return (
    <div style={{ border: '1px solid #ddd', borderRadius: 6, padding: 8 }}>
      <Stack direction="row" spacing={1} sx={{ mb: 1, flexWrap: 'wrap' }}>
        <Button size="small" onClick={() => editor?.chain().focus().toggleBold().run()} disabled={!editor}>Bold</Button>
        <Button size="small" onClick={() => editor?.chain().focus().toggleItalic().run()} disabled={!editor}>Italic</Button>
        <Button size="small" onClick={() => editor?.chain().focus().toggleHeading({ level: 2 }).run()} disabled={!editor}>H2</Button>
        <Button size="small" onClick={() => editor?.chain().focus().toggleHeading({ level: 3 }).run()} disabled={!editor}>H3</Button>
        <Button size="small" onClick={() => editor?.chain().focus().toggleBulletList().run()} disabled={!editor}>• List</Button>
        <Button size="small" onClick={() => editor?.chain().focus().toggleOrderedList().run()} disabled={!editor}>1. List</Button>
        <Button size="small" onClick={() => editor?.chain().focus().toggleCodeBlock().run()} disabled={!editor}>Code</Button>
        <Button size="small" onClick={() => {
          if (!editor) return;
          const href = prompt('Enter link URL');
          if (!href) {
            editor.chain().focus().extendMarkRange('link').unsetLink().run();
          } else {
            editor.chain().focus().extendMarkRange('link').setLink({ href }).run();
          }
        }} disabled={!editor}>Link</Button>
        <Button size="small" onClick={() => editor?.chain().focus().clearNodes().unsetAllMarks().run()} disabled={!editor}>Clear</Button>
        <Button size="small" variant="outlined" onClick={async () => {
          if (!editor) return;
          const input = document.createElement('input');
          input.type = 'file';
          input.accept = 'image/*';
          input.onchange = async () => {
            const file = input.files?.[0];
            if (!file) return;
            const fd = new FormData();
            fd.append('image', file, file.name);
            const res = await fetch('/api/media/image', { method: 'POST', body: fd });
            if (!res.ok) return console.error('Image upload failed', await res.text());
            const data = await res.json();
            const url = data.url as string | undefined;
            if (url) editor.chain().focus().setImage({ src: url, alt: file.name }).run();
          };
          input.click();
        }}>Insert Image</Button>
      </Stack>
      <EditorContent editor={editor} />
    </div>
  );
});

export default RichEditor;
