import { useEffect, useRef, useState, createContext } from '@wordpress/element';

const TinyMCEEditor = ({ label, content, onEditorChange }) => {
	const [editorContent, setEditorContent] = useState(content);
	const editorRef = useRef(null);
	const uniqueId = useRef(`wp-editor-area-${Math.random().toString(36).substr(2, 9)}`); // Unique ID for each editor instance

	useEffect(() => {
		// Wait until the editorRef is available
		if (editorRef.current) {
			// Initialize TinyMCE after ensuring the ref is available
			wp?.editor?.initialize(uniqueId.current, {
				tinymce: {
					mediaButtons: true,
					toolbar1:
						'formatselect,bold,italic,strikethrough,forecolor,backcolor,bullist,numlist,blockquote,hr,alignleft,aligncenter,alignright,link,unlink,media,spellchecker,fullscreen,wp_adv',
					toolbar2:
						'underline,alignjustify,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help',
					plugins:
						'lists,fullscreen,paste,wpautoresize,wpdialogs,wpeditimage,wpgallery,wplink,wptextpattern,wpview,wordpress,wpemoji,media,textcolor,hr',
					wpautop: true,
					menubar: false,
					branding: false,
					height: 250,
					wp_adv_height: 48,
					quicktags: {
						buttons: 'strong,em,link,block,del,ins,img,ul,ol,li,code,close',
					},
					setup: (editor) => {
						editor.on('init', () => {
							editor.setContent(content || '');
						});
						editor.on('change', () => {
							const newContent = editor.getContent();
							setEditorContent(newContent);
							onEditorChange(newContent);
						});
					},
				},
			});
		}

		// Cleanup when the component unmounts
		return () => {
			if (window.tinymce) {
				window.tinymce.remove(editorRef.current);
			}
		};
	}, [editorRef.current, content]);

	useEffect(() => {
		if (window.tinymce && window.tinymce.activeEditor) {
			window.tinymce.activeEditor.setContent(content || '');
		}
	}, [content]);

	return (
		<div className='my-3'>
			<label htmlFor={uniqueId.current} className='mb-2'>
				{label}
			</label>
			<textarea
				id={uniqueId.current}
				ref={editorRef} // Attach the ref to the textarea
				defaultValue={editorContent}
				onChange={() => {
					onEditorChange(editorRef.current.value);
				}}
			/>
		</div>
	);
};

export default TinyMCEEditor;
