import React, { useEffect, useRef } from 'react';

const WordPressEditor = ({ 
    id, 
    value = '', 
    onChange, 
    placeholder = 'Enter content...', 
    height = 200,
    label = null 
}) => {
    const editorRef = useRef(null);
    const isInitialized = useRef(false);

    useEffect(() => {
        // Ensure wp and tinymce are available
        if (typeof wp === 'undefined' || typeof wp.editor === 'undefined') {
            console.warn('WordPress editor not available');
            return;
        }

        // Initialize the editor
        const initEditor = () => {
            if (isInitialized.current) return;

            const settings = {
                tinymce: {
                    wpautop: true,
                    plugins: 'charmap colorpicker hr lists paste tabfocus textcolor fullscreen wordpress wpautoresize wpeditimage wpemoji wpgallery wplink wptextpattern',
                    toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,wp_more,spellchecker,fullscreen,wp_adv',
                    toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help',
                    height: height,
                    resize: true,
                    menubar: false,
                    branding: false,
                    relative_urls: false,
                    remove_script_host: false,
                    convert_urls: false,
                    browser_spellcheck: true,
                    fix_list_elements: true,
                    entities: '38,amp,60,lt,62,gt',
                    entity_encoding: 'raw',
                    keep_styles: false,
                    paste_webkit_styles: 'font-weight font-style color',
                    paste_remove_styles_if_webkit: true,
                    paste_strip_class_attributes: 'all',
                    setup: function(editor) {
                        editor.on('change keyup', function() {
                            const content = editor.getContent();
                            if (onChange) {
                                onChange(content);
                            }
                        });

                        editor.on('init', function() {
                            editor.setContent(value || '');
                        });
                    }
                },
                quicktags: {
                    buttons: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close'
                },
                mediaButtons: true
            };

            wp.editor.initialize(id, settings);
            isInitialized.current = true;
        };

        // Small delay to ensure DOM is ready
        setTimeout(initEditor, 100);

        // Cleanup function
        return () => {
            if (isInitialized.current && wp.editor) {
                wp.editor.remove(id);
                isInitialized.current = false;
            }
        };
    }, [id, height]);

    // Update content when value prop changes
    useEffect(() => {
        if (isInitialized.current && typeof tinymce !== 'undefined') {
            const editor = tinymce.get(id);
            if (editor && editor.getContent() !== value) {
                editor.setContent(value || '');
            }
        }
    }, [value, id]);

    return (
        <div className="wp-editor-container">
            {label && <label htmlFor={id}>{label}</label>}
            <textarea
                ref={editorRef}
                id={id}
                name={id}
                defaultValue={value}
                placeholder={placeholder}
                style={{ width: '100%', minHeight: `${height}px` }}
            />
        </div>
    );
};

export default WordPressEditor;