import Link from '@tiptap/extension-link';
import { EditorContent, useEditor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import { Bold, Heading2, Italic, Link2, List, ListOrdered } from 'lucide-react';
import { cn } from '@/lib/utils';

/** Minimal rich-text editor (T&Cs, signatures). HTML is sanitised server-side. */
export function RichTextEditor({ value, onChange, disabled, id, label }: {
    value: string; onChange: (html: string) => void; disabled?: boolean; id?: string; label: string;
}) {
    const editor = useEditor({
        extensions: [StarterKit.configure({ link: false }), Link.configure({ openOnClick: false })],
        content: value || '',
        editable: !disabled,
        immediatelyRender: false,
        editorProps: { attributes: { class: 'prose-app min-h-32 px-3 py-2 text-sm', 'aria-label': label, id: id ?? '' } },
        onUpdate: ({ editor }) => onChange(editor.isEmpty ? '' : editor.getHTML()),
    });

    const btn = (active: boolean, onClick: () => void, icon: React.ReactNode, title: string) => (
        <button type="button" title={title} aria-label={title} aria-pressed={active} disabled={disabled} onClick={onClick}
            className={cn('rounded p-1.5 hover:bg-stone-100', active && 'bg-stone-200')}>{icon}</button>
    );

    return (
        <div className={cn('rounded-md border border-line-strong bg-surface', disabled && 'bg-stone-50')}>
            {editor && !disabled && (
                <div className="flex gap-1 border-b border-line px-1 py-1">
                    {btn(editor.isActive('bold'), () => editor.chain().focus().toggleBold().run(), <Bold className="h-4 w-4" />, 'Bold')}
                    {btn(editor.isActive('italic'), () => editor.chain().focus().toggleItalic().run(), <Italic className="h-4 w-4" />, 'Italic')}
                    {btn(editor.isActive('heading', { level: 2 }), () => editor.chain().focus().toggleHeading({ level: 2 }).run(), <Heading2 className="h-4 w-4" />, 'Heading')}
                    {btn(editor.isActive('bulletList'), () => editor.chain().focus().toggleBulletList().run(), <List className="h-4 w-4" />, 'Bullet list')}
                    {btn(editor.isActive('orderedList'), () => editor.chain().focus().toggleOrderedList().run(), <ListOrdered className="h-4 w-4" />, 'Numbered list')}
                    {btn(editor.isActive('link'), () => {
                        const url = window.prompt('Link URL (https://…)', editor.getAttributes('link').href ?? 'https://');
                        if (url === null) return;
                        if (url === '') editor.chain().focus().unsetLink().run();
                        else editor.chain().focus().setLink({ href: url }).run();
                    }, <Link2 className="h-4 w-4" />, 'Link')}
                </div>
            )}
            <EditorContent editor={editor} />
        </div>
    );
}
