import { useEditor, EditorContent } from '@tiptap/react';
import { useEffect } from 'react';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import Link from '@tiptap/extension-link';
import Placeholder from '@tiptap/extension-placeholder';
import { 
    Bold, Italic, Underline as UnderlineIcon, 
    List, ListOrdered, Link as LinkIcon, 
    Heading1, Heading2, Heading3, Quote, Undo, Redo 
} from 'lucide-react';

interface RichTextEditorProps {
    value: string;
    onChange: (content: string) => void;
    placeholder?: string;
    editorClassName?: string;
}

const MenuBar = ({ editor }: { editor: any }) => {
    if (!editor) return null;

    const setLink = () => {
        const previousUrl = editor.getAttributes('link').href;
        const url = window.prompt('URL', previousUrl);

        if (url === null) return;
        if (url === '') {
            editor.chain().focus().extendMarkRange('link').unsetLink().run();
            return;
        }

        editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
    };

    const buttons = [
        { icon: Bold, action: () => editor.chain().focus().toggleBold().run(), active: 'bold' },
        { icon: Italic, action: () => editor.chain().focus().toggleItalic().run(), active: 'italic' },
        { icon: UnderlineIcon, action: () => editor.chain().focus().toggleUnderline().run(), active: 'underline' },
        { divider: true },
        { icon: Heading1, action: () => editor.chain().focus().toggleHeading({ level: 1 }).run(), active: { level: 1 } },
        { icon: Heading2, action: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), active: { level: 2 } },
        { icon: Heading3, action: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), active: { level: 3 } },
        { divider: true },
        { icon: List, action: () => editor.chain().focus().toggleBulletList().run(), active: 'bulletList' },
        { icon: ListOrdered, action: () => editor.chain().focus().toggleOrderedList().run(), active: 'orderedList' },
        { divider: true },
        { icon: Quote, action: () => editor.chain().focus().toggleBlockquote().run(), active: 'blockquote' },
        { icon: LinkIcon, action: setLink, active: 'link' },
        { divider: true },
        { icon: Undo, action: () => editor.chain().focus().undo().run() },
        { icon: Redo, action: () => editor.chain().focus().redo().run() },
    ];

    return (
        <div className="flex flex-wrap items-center gap-1 p-2 border-b border-border bg-[#FAFAF8]">
            {buttons.map((btn, i) => {
                if (btn.divider) {
                    return <div key={i} className="w-px h-4 bg-border mx-1" />;
                }

                const Icon = btn.icon;
                
                return (
                    <button
                        key={i}
                        type="button"
                        onClick={btn.action}
                        className={`p-2 rounded-lg transition-colors ${
                            btn.active && editor.isActive(btn.active) 
                            ? 'bg-primary text-white' 
                            : 'text-[#8C92AC] hover:bg-primary/10 hover:text-primary'
                        }`}
                    >
                        {Icon && <Icon className="h-4 w-4" />}
                    </button>
                );
            })}
        </div>
    );
};

export default function RichTextEditor({ value, onChange, placeholder = 'Write something...', editorClassName }: RichTextEditorProps) {
    const editor = useEditor({
        extensions: [
            StarterKit,
            Underline,
            Link.configure({
                openOnClick: false,
                HTMLAttributes: {
                    class: 'text-primary underline cursor-pointer',
                },
            }),
            Placeholder.configure({
                placeholder,
            }),
        ],
        content: value,
        onUpdate: ({ editor }) => {
            onChange(editor.getHTML());
        },
        editorProps: {
            attributes: {
                class: editorClassName || 'prose prose-sm sm:prose lg:prose-lg xl:prose-2xl focus:outline-none min-h-[300px] p-5 max-w-none',
            },
        },
    });

    // Keep editor content in sync with external value
    useEffect(() => {
        if (editor && value !== editor.getHTML()) {
            editor.commands.setContent(value);
        }
    }, [value, editor]);

    return (
        <div className="rounded-2xl border border-border bg-white flex flex-col focus-within:ring-2 focus-within:ring-primary/20 transition-all overflow-hidden">
            <div className="sticky top-0 z-10 bg-white">
                <MenuBar editor={editor} />
            </div>
            <div className="max-h-[600px] overflow-y-auto bg-white custom-scrollbar">
                <EditorContent editor={editor} />
            </div>
        </div>
    );
}
