import React, { useRef, useEffect } from 'react';

const WYSIWYGEditor = ({
    value,
    onChange,
    placeholder = "Enter content...",
    height = "300px",
    id,
    className = ""
}) => {
    const editorRef = useRef(null);
    const toolbarRef = useRef(null);

    useEffect(() => {
        // Initialize the editor content
        if (editorRef.current && value !== editorRef.current.innerHTML) {
            editorRef.current.innerHTML = value || '';
        }
    }, [value]);

    const execCommand = (command, value = null) => {
        document.execCommand(command, false, value);
        editorRef.current.focus();
        handleContentChange();
    };

    const handleContentChange = () => {
        if (editorRef.current && onChange) {
            onChange(editorRef.current.innerHTML);
        }
    };

    const insertLink = () => {
        const url = prompt('Enter URL:');
        if (url) {
            execCommand('createLink', url);
        }
    };

    const insertImage = async () => {
        if (typeof wp !== 'undefined' && wp.media) {
            const mediaUploader = wp.media({
                title: 'Select Image',
                button: {
                    text: 'Insert Image'
                },
                multiple: false,
                library: {
                    type: 'image'
                }
            });

            mediaUploader.on('select', function () {
                const attachment = mediaUploader.state().get('selection').first().toJSON();
                const imgHtml = `<img src="${attachment.url}" alt="${attachment.alt || ''}" style="max-width: 100%; height: auto;" />`;

                // Insert the image at cursor position
                if (document.queryCommandSupported('insertHTML')) {
                    execCommand('insertHTML', imgHtml);
                } else {
                    // Fallback for older browsers
                    const selection = window.getSelection();
                    if (selection.rangeCount > 0) {
                        const range = selection.getRangeAt(0);
                        range.deleteContents();
                        const imgElement = document.createElement('div');
                        imgElement.innerHTML = imgHtml;
                        range.insertNode(imgElement.firstChild);
                    }
                }
            });

            mediaUploader.open();
        } else {
            // Fallback to URL input
            const url = prompt('Enter image URL:');
            if (url) {
                const imgHtml = `<img src="${url}" alt="" style="max-width: 100%; height: auto;" />`;
                execCommand('insertHTML', imgHtml);
            }
        }
    };

    const insertVideo = () => {
        const url = prompt('Enter video URL (YouTube, Vimeo, or direct link):');
        if (url) {
            let videoEmbed = '';

            // YouTube
            if (url.includes('youtube.com') || url.includes('youtu.be')) {
                const videoId = url.includes('youtu.be')
                    ? url.split('/').pop()
                    : url.split('v=')[1]?.split('&')[0];
                if (videoId) {
                    videoEmbed = `<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`;
                }
            }
            // Vimeo
            else if (url.includes('vimeo.com')) {
                const videoId = url.split('/').pop();
                videoEmbed = `<iframe src="https://player.vimeo.com/video/${videoId}" width="560" height="315" frameborder="0" allowfullscreen></iframe>`;
            }
            // Direct video link
            else {
                videoEmbed = `<video controls style="max-width: 100%; height: auto;"><source src="${url}" type="video/mp4">Your browser does not support the video tag.</video>`;
            }

            if (videoEmbed) {
                execCommand('insertHTML', videoEmbed);
            }
        }
    };

    const toolbarButtons = [
        { command: 'bold', icon: '𝐁', title: 'Bold' },
        { command: 'italic', icon: '𝐼', title: 'Italic' },
        { command: 'underline', icon: '𝐔', title: 'Underline' },
        { command: 'strikeThrough', icon: '𝐒', title: 'Strikethrough' },
        { type: 'separator' },
        { command: 'justifyLeft', icon: '⬅', title: 'Align Left' },
        { command: 'justifyCenter', icon: '⬌', title: 'Align Center' },
        { command: 'justifyRight', icon: '➡', title: 'Align Right' },
        { command: 'justifyFull', icon: '⬍', title: 'Justify' },
        { type: 'separator' },
        { command: 'insertUnorderedList', icon: '•', title: 'Bullet List' },
        { command: 'insertOrderedList', icon: '1.', title: 'Numbered List' },
        { command: 'outdent', icon: '⬅', title: 'Decrease Indent' },
        { command: 'indent', icon: '➡', title: 'Increase Indent' },
        { type: 'separator' },
        { command: 'link', icon: '🔗', title: 'Insert Link', action: insertLink },
        { command: 'image', icon: '🖼', title: 'Insert Image', action: insertImage },
        { command: 'video', icon: '🎥', title: 'Insert Video', action: insertVideo },
        { type: 'separator' },
        { command: 'removeFormat', icon: '🧹', title: 'Clear Formatting' },
        { command: 'undo', icon: '↶', title: 'Undo' },
        { command: 'redo', icon: '↷', title: 'Redo' }
    ];

    const formatBlocks = [
        { value: 'div', label: 'Normal' },
        { value: 'h1', label: 'Heading 1' },
        { value: 'h2', label: 'Heading 2' },
        { value: 'h3', label: 'Heading 3' },
        { value: 'h4', label: 'Heading 4' },
        { value: 'h5', label: 'Heading 5' },
        { value: 'h6', label: 'Heading 6' },
        { value: 'p', label: 'Paragraph' },
        { value: 'blockquote', label: 'Quote' }
    ];

    return (
        <div className={`wysiwyg-editor ${className}`}>
            <div className="wysiwyg-toolbar" ref={toolbarRef}>
                <select
                    onChange={(e) => execCommand('formatBlock', `<${e.target.value}>`)}
                    className="format-select"
                >
                    {formatBlocks.map(block => (
                        <option key={block.value} value={block.value}>
                            {block.label}
                        </option>
                    ))}
                </select>

                {toolbarButtons.map((button, index) => {
                    if (button.type === 'separator') {
                        return <div key={index} className="toolbar-separator" />;
                    }

                    return (
                        <button
                            key={button.command}
                            type="button"
                            className="toolbar-btn"
                            title={button.title}
                            onClick={() => button.action ? button.action() : execCommand(button.command)}
                        >
                            {button.icon}
                        </button>
                    );
                })}
            </div>

            <div
                ref={editorRef}
                className="wysiwyg-content"
                contentEditable
                style={{ minHeight: height }}
                onInput={handleContentChange}
                onBlur={handleContentChange}
                data-placeholder={placeholder}
                suppressContentEditableWarning={true}
            />
        </div>
    );
};

export default WYSIWYGEditor;