import React from 'react';
import { useEditor, EditorContent, Editor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';

interface RichTextEditorProps {
    value: string;
    onChange: (html: string) => void;
    ariaLabel?: string;
    disabled?: boolean;
}

export const RichTextEditor: React.FC<RichTextEditorProps> = ({
    value,
    onChange,
    ariaLabel,
    disabled = false,
}) => {
    const editor = useEditor({
        extensions: [
            StarterKit,
        ],
        content: value,
        editable: !disabled,
        onUpdate: ({ editor }) => {
            onChange(editor.getHTML());
        },
        editorProps: {
            attributes: {
                class: 'prose prose-sm focus:outline-none min-h-[80px] px-3 py-2',
                ...(ariaLabel ? { 'aria-label': ariaLabel } : {}),
            },
        },
    });

    // Handle external value changes (reset)
    React.useEffect(() => {
        if (editor && value === '') {
            editor.commands.setContent('');
        }
    }, [value, editor]);

    React.useEffect(() => {
        editor?.setEditable(!disabled);
    }, [disabled, editor]);

    if (!editor) {
        return null;
    }

    return (
        <div
            aria-disabled={disabled || undefined}
            className={`border border-slate-300 rounded-lg overflow-hidden transition-all ${disabled
                ? 'bg-slate-50 opacity-60'
                : 'bg-white focus-within:ring-2 focus-within:ring-blue-500/20 focus-within:border-blue-500'
            }`}
        >
            <MenuBar editor={editor} disabled={disabled} />
            <div className={disabled ? 'bg-slate-50' : 'bg-white'}>
                <EditorContent editor={editor} />
            </div>
        </div>
    );
};

// Simple Menu Bar
const MenuBar = ({ editor, disabled }: { editor: Editor | null; disabled: boolean }) => {
    if (!editor) {
        return null;
    }

    const Button = ({ onClick, isActive, children, title }: { onClick: () => void; isActive: boolean; children: React.ReactNode; title: string }) => (
        <button
            onClick={onClick}
            disabled={disabled}
            className={`p-1.5 rounded disabled:cursor-not-allowed ${disabled ? '' : 'hover:bg-slate-100'} ${isActive ? 'bg-slate-200 text-slate-900' : 'text-slate-500'}`}
            title={title}
            type="button"
        >
            {children}
        </button>
    );

    return (
        <div className="flex gap-1 p-2 border-b border-slate-100 bg-slate-50 items-center">
            <Button
                onClick={() => editor.chain().focus().toggleBold().run()}
                isActive={editor.isActive('bold')}
                title="Bold"
            >
                <span className="font-bold">B</span>
            </Button>
            <Button
                onClick={() => editor.chain().focus().toggleItalic().run()}
                isActive={editor.isActive('italic')}
                title="Italic"
            >
                <span className="italic">I</span>
            </Button>
            <Button
                onClick={() => editor.chain().focus().toggleBulletList().run()}
                isActive={editor.isActive('bulletList')}
                title="Bullet List"
            >
                <span>• List</span>
            </Button>
            <Button
                onClick={() => editor.chain().focus().toggleOrderedList().run()}
                isActive={editor.isActive('orderedList')}
                title="Number List"
            >
                <span>1. List</span>
            </Button>
        </div>
    );
};
