"use client";
import Link from "@tiptap/extension-link";
import Underline from "@tiptap/extension-underline";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import ToolBar from "~/components/tip-tap/toolbar";

function Tiptap({
	value,
	onChange,
	id,
}: {
	value: string;
	onChange: (richText: string) => void;
	id: string;
}) {
	const editor = useEditor({
		content: value,
		editorProps: {
			attributes: {
				class:
					"prose dark:prose-invert [&_*]:text-foreground max-w-none overflow-auto h-full w-full text-foreground rounded-md border min-h-[30rem] max-h-[50rem] border-input bg-background focus:ring-offset-2 disabled:cursor-not-allows disabled:opacity-50 p-2",
			},
		},
		extensions: [
			StarterKit,
			Underline,
			Link.configure({
				defaultProtocol: "https",
			}),
		],
		immediatelyRender: false,
		onUpdate({ editor }) {
			onChange(editor.getHTML());
		},
	});

	if (!editor) {
		return null;
	}

	return (
		<div
			className="flex h-full min-h-62.5 w-full flex-col justify-stretch"
			id={id}
		>
			<ToolBar editor={editor} />
			<EditorContent editor={editor} />
		</div>
	);
}

export default Tiptap;
