"use client";

import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import { Bold, Italic, List, ListOrdered, Heading1, Heading2, Heading3, Undo, Redo } from 'lucide-react'
import { useEffect } from 'react';

interface RichTextEditorProps {
    content: string;
    onChange: (html: string) => void;
    error?: boolean;
}

export function RichTextEditor({ content, onChange, error }: RichTextEditorProps) {
    const editor = useEditor({
        extensions: [
            StarterKit.configure({
                heading: {
                    levels: [1, 2, 3],
                },
            }),
        ],
        content,
        immediatelyRender: false,
        editorProps: {
            attributes: {
                class: 'prose prose-slate prose-p:my-1 prose-headings:my-2 prose-ul:my-1 prose-ol:my-1 prose-li:my-0 focus:outline-none min-h-[300px] w-full max-w-none',
            },
        },
        onUpdate: ({ editor }) => {
            onChange(editor.getHTML());
        },
    })

    // Sync external content changes (e.g. from drafts/Form Reset)
    useEffect(() => {
        if (editor && content !== editor.getHTML()) {
            editor.commands.setContent(content, { emitUpdate: false })
        }
    }, [content, editor])

    if (!editor) {
        return null
    }

    return (
        <div className={`overflow-hidden rounded-xl border transition-all ${error ? 'border-red-300 focus-within:border-red-500 focus-within:ring-1 focus-within:ring-red-500/20' : 'border-slate-200 focus-within:border-primary focus-within:ring-1 focus-within:ring-primary/20'}`}>
            {/* Sticky Toolbar */}
            <div className="bg-slate-50 border-b border-slate-200 p-2 flex flex-wrap gap-1 sticky top-0 z-10">
                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().toggleBold().run(); }}
                    disabled={!editor.can().chain().focus().toggleBold().run()}
                    className={`p-2 rounded-lg transition-colors ${editor.isActive('bold') ? 'bg-slate-200 text-slate-900' : 'text-slate-600 hover:bg-slate-100'}`}
                    title="Bold"
                >
                    <Bold className="w-4 h-4" />
                </button>
                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().toggleItalic().run(); }}
                    disabled={!editor.can().chain().focus().toggleItalic().run()}
                    className={`p-2 rounded-lg transition-colors ${editor.isActive('italic') ? 'bg-slate-200 text-slate-900' : 'text-slate-600 hover:bg-slate-100'}`}
                    title="Italic"
                >
                    <Italic className="w-4 h-4" />
                </button>

                <div className="w-px h-6 bg-slate-300 my-auto mx-1" />

                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().toggleHeading({ level: 1 }).run(); }}
                    className={`p-2 rounded-lg transition-colors ${editor.isActive('heading', { level: 1 }) ? 'bg-slate-200 text-slate-900' : 'text-slate-600 hover:bg-slate-100'}`}
                    title="Heading 1"
                >
                    <Heading1 className="w-4 h-4" />
                </button>
                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().toggleHeading({ level: 2 }).run(); }}
                    className={`p-2 rounded-lg transition-colors ${editor.isActive('heading', { level: 2 }) ? 'bg-slate-200 text-slate-900' : 'text-slate-600 hover:bg-slate-100'}`}
                    title="Heading 2"
                >
                    <Heading2 className="w-4 h-4" />
                </button>
                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().toggleHeading({ level: 3 }).run(); }}
                    className={`p-2 rounded-lg transition-colors ${editor.isActive('heading', { level: 3 }) ? 'bg-slate-200 text-slate-900' : 'text-slate-600 hover:bg-slate-100'}`}
                    title="Heading 3"
                >
                    <Heading3 className="w-4 h-4" />
                </button>

                <div className="w-px h-6 bg-slate-300 my-auto mx-1" />

                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().toggleBulletList().run(); }}
                    className={`p-2 rounded-lg transition-colors ${editor.isActive('bulletList') ? 'bg-slate-200 text-slate-900' : 'text-slate-600 hover:bg-slate-100'}`}
                    title="Bullet List"
                >
                    <List className="w-4 h-4" />
                </button>
                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().toggleOrderedList().run(); }}
                    className={`p-2 rounded-lg transition-colors ${editor.isActive('orderedList') ? 'bg-slate-200 text-slate-900' : 'text-slate-600 hover:bg-slate-100'}`}
                    title="Numbered List"
                >
                    <ListOrdered className="w-4 h-4" />
                </button>

                <div className="w-px h-6 bg-slate-300 my-auto mx-1" />

                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().undo().run(); }}
                    disabled={!editor.can().chain().focus().undo().run()}
                    className="p-2 rounded-lg text-slate-600 hover:bg-slate-100 disabled:opacity-30 transition-colors ml-auto md:ml-0"
                    title="Undo"
                >
                    <Undo className="w-4 h-4" />
                </button>
                <button
                    type="button"
                    onClick={(e) => { e.preventDefault(); editor.chain().focus().redo().run(); }}
                    disabled={!editor.can().chain().focus().redo().run()}
                    className="p-2 rounded-lg text-slate-600 hover:bg-slate-100 disabled:opacity-30 transition-colors"
                    title="Redo"
                >
                    <Redo className="w-4 h-4" />
                </button>

            </div>

            {/* Editor Content Area */}
            <div className="p-4 bg-white cursor-text min-h-[300px]" onClick={() => editor.commands.focus()}>
                <EditorContent editor={editor} />
            </div>
        </div>
    )
}
