"use client";

import * as React from "react";
import {
	MDXEditor,
	headingsPlugin,
	listsPlugin,
	quotePlugin,
	thematicBreakPlugin,
	markdownShortcutPlugin,
	toolbarPlugin,
	linkPlugin,
	linkDialogPlugin,
	type MDXEditorMethods,
	KitchenSinkToolbar,
	tablePlugin,
	imagePlugin,
	frontmatterPlugin,
	codeBlockPlugin,
	directivesPlugin,
	AdmonitionDirectiveDescriptor,
} from "@mdxeditor/editor";

import { cn } from "@/lib/utils";
import { Card } from "@/components/ui/card";

interface EditorProps {
	markdown: string;
	onChange?: (markdown: string) => void;
	className?: string;
}

export function Editor({ markdown, onChange, className }: EditorProps) {
	const ref = React.useRef<MDXEditorMethods>(null);

	const onChangeDebounce = (content: string) => {
		localStorage.setItem("blog_draft", content);
	};

	return (
		<Card className={cn("border rounded-lg overflow-hidden", className)}>
			<MDXEditor
				ref={ref}
				className="mdx-editor dark-theme dark-editor prose dark:prose-invert p-4"
				markdown={markdown}
				onChange={onChangeDebounce}
				spellCheck
				plugins={[
					toolbarPlugin({
						toolbarContents: () => <KitchenSinkToolbar />,
					}),
					listsPlugin(),
					quotePlugin(),
					headingsPlugin(),
					linkPlugin(),
					linkDialogPlugin(),
					// eslint-disable-next-line @typescript-eslint/require-await
					imagePlugin({
						imageUploadHandler: async () => "/sample-image.png",
					}),
					tablePlugin(),
					thematicBreakPlugin(),
					frontmatterPlugin(),
					codeBlockPlugin({ defaultCodeBlockLanguage: "txt" }),
					directivesPlugin({
						directiveDescriptors: [AdmonitionDirectiveDescriptor],
					}),
					markdownShortcutPlugin(),
				]}
			/>
		</Card>
	);
}
