import { useState } from "react";
import { useFormContext } from "react-hook-form";
import {
	FormControl,
	FormDescription,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "@/components/ui/form";
import { RichTextEditor } from "@/components/ui/rich-text-editor";

interface BlogEditorProps {
	name: string;
	label?: string;
	description?: string;
	placeholder?: string;
}

/**
 * Blog editor component that uses the RichTextEditor
 *
 * This component wraps the RichTextEditor with a form field and adds
 * write/preview tabs functionality specific for blog content.
 */
export function BlogEditor({
	name,
	label = "Content",
	description = "You can use markdown formatting. The article will be attributed to your account.",
	placeholder = "Write your article content here...",
}: BlogEditorProps) {
	const form = useFormContext();
	const [_content, setContent] = useState(form.getValues(name) || "");

	// Update form field when content changes
	const handleContentChange = (value: string) => {
		setContent(value);
		form.setValue(name, value, { shouldValidate: true, shouldDirty: true });
	};

	return (
		<FormField
			control={form.control}
			name={name}
			render={({ field }) => (
				<FormItem>
					<FormLabel>{label}</FormLabel>
					<FormControl>
						<RichTextEditor
							value={field.value || ""}
							onChange={handleContentChange}
							placeholder={placeholder}
							height="min-h-96"
							className="font-serif leading-relaxed"
						/>
					</FormControl>
					<FormDescription>{description}</FormDescription>
					<FormMessage />
				</FormItem>
			)}
		/>
	);
}
