
import { useEditor, EditorContent, EditorContext } from '@tiptap/react'
import TextAlign from '@tiptap/extension-text-align'
import StarterKit from '@tiptap/starter-kit'
import { useMemo } from 'react'
import MenuBar from './MenuBar'
import { cn } from '@/lib/utils'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'

type Props = {
    label?: string
    requred?: boolean
    value?: string | null
    onChange?: (html: string) => void
    error?: string
    className?: string
}
export default function RichTextEditor({ value = '', onChange, className, label, requred, error }: Props) {
    const editor = useEditor({
        extensions: [
            StarterKit.configure({
                bulletList: {
                    HTMLAttributes: {
                        class: 'list-disc pl-4',
                    },
                },
                orderedList: {
                    HTMLAttributes: {
                        class: 'list-decimal pl-4',
                    },
                }
            }),
            TextAlign.configure({
                types: ['heading', 'paragraph'],
            }),

        ], // define your extension array
        editorProps: {
            attributes: {
                class: "border p-2 min-h-[240px]"
            }
        },
        content: value,
        onUpdate: ({ editor }) => {
            onChange?.(editor.getHTML()) // ✅ only HTML
        },
    })



    // Memoize the provider value to avoid unnecessary re-renders
    const providerValue = useMemo(() => ({ editor }), [editor])
    console.log(providerValue.editor.getHTML());

    return (
        <div className={cn('bg-card border rounded-sm p-4  space-y-2 h-fit text-sm max-w-3xl', className)}>
            <EditorContext.Provider value={providerValue} >
                {label && <>
                    <Label className=''>{label} {requred && <span className="text-destructive">*</span>}</Label>
                    <Separator />
                </>}
                <MenuBar editor={providerValue.editor} />
                <EditorContent editor={providerValue.editor} className='h-fit rich-text rounded-sm' />
                {/* <FloatingMenu editor={editor}>This is the floating menu</FloatingMenu> */}
                {/* <BubbleMenu editor={editor}>This is the bubble menu</BubbleMenu> */}
                {error && <p className='text-red-600 text-sm'>{error}</p>}
            </EditorContext.Provider>
        </div>
    )
}
