"use client";

import * as React from "react";

import { cn } from "@/lib/utils";
import { Card } from "@/components/ui/card";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Underline from "@tiptap/extension-underline";
import Link from "@tiptap/extension-link";
import TTImage from "@tiptap/extension-image";
import TextAlign from "@tiptap/extension-text-align";
import Youtube from "@tiptap/extension-youtube";
import Dropcursor from "@tiptap/extension-dropcursor";
import { EditorMenu } from "./editor-menu";

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

export function Editor({ content, onChange, className }: EditorProps) {
	const editor = useEditor({
		extensions: [
			StarterKit,
			Underline,
			Link,
			Youtube,
			Dropcursor,
			TTImage.configure({
				HTMLAttributes: {
					class: "max-w-full w-auto h-auto resize overflow-auto",
				},
			}),
			TextAlign.configure({
				alignments: ["left", "center", "right", "justify"],
				defaultAlignment: "justify",
				types: ["heading", "paragraph"],
			}),
		],
		content,
		immediatelyRender: false,
		editorProps: {
			attributes: {
				class: "prose prose-sm sm:prose-base lg:prose-lg xl:prose-2xl m-5 focus:outline-none dark:prose-invert",
			},
		},
		onUpdate: ({ editor }) => {
			console.log("Update");
			localStorage.setItem("blog_draft", editor.getHTML());
		},
	});

	if (!editor) {
		return null;
	}

	return (
		<Card className={cn("border rounded-lg overflow-hidden", className)}>
			<EditorMenu editor={editor} />
			<EditorContent editor={editor} />
		</Card>
	);
}
