import React from "react";
import { RawEditorOptions, TinyMCE, Editor } from "./tinymce";
import { twMerge } from "tailwind-merge";

export type TinyMCEEditorProps = {
    tinyMCE?: TinyMCE | null;
    options?: RawEditorOptions;
    editorRef?: React.MutableRefObject<Editor | null>;
    setEditor?: React.Dispatch<React.SetStateAction<Editor>>;
    wrapperProps?: React.DetailedHTMLProps<
        React.HTMLAttributes<HTMLDivElement>,
        HTMLDivElement
    >;
    defaultValue?: string;
};

let interval: any;

/**
 * # Tiny MCE Editor Component
 * @className_wrapper twui-rte-wrapper
 */
export default function TinyMCEEditor({
    options,
    editorRef,
    setEditor,
    tinyMCE,
    wrapperProps,
    defaultValue,
}: TinyMCEEditorProps) {
    const editorComponentRef = React.useRef<HTMLDivElement>(null);

    const FINAL_HEIGHT = options?.height || 500;

    React.useEffect(() => {
        if (!editorComponentRef.current) {
            return;
        }

        tinyMCE?.init({
            height: FINAL_HEIGHT,
            menubar: false,
            plugins: [
                "advlist lists link image charmap print preview anchor",
                "searchreplace visualblocks code fullscreen",
                "insertdatetime media table paste code help wordcount",
            ],
            toolbar:
                "undo redo | blocks | bold italic | bullist numlist outdent indent | removeformat",
            content_style:
                "body { font-family:Helvetica,Arial,sans-serif; font-size:14px }",
            init_instance_callback: (editor) => {
                setEditor?.(editor as any);
                if (editorRef) editorRef.current = editor as any;
                if (defaultValue) editor.setContent(defaultValue);
            },
            base_url: "https://datasquirel.com/tinymce-public",
            body_class: "twui-tinymce",
            ...options,
            license_key: "gpl",
            target: editorComponentRef.current,
        });
    }, [tinyMCE]);

    return (
        <div
            {...wrapperProps}
            ref={editorComponentRef}
            style={{
                height: FINAL_HEIGHT + "px",
                ...wrapperProps?.style,
            }}
            className={twMerge(
                "bg-slate-200 dark:bg-slate-700 rounded-sm",
                "twui-rte-wrapper"
            )}
        />
    );
}